
原題 | Unravelling binary arithmetic operations in Python
作者 | Brett Cannon
譯者 | 豌豆花下貓
來源 | Python貓
聲明 | 本翻譯是出于交流學習的目的,基于 CC BY-NC-SA 4.0 授權協議。為便于閱讀,內容略有改動。
大家對我解讀屬性訪問的博客文章反應熱烈,這啟發了我再寫一篇關于 python 有多少語法實際上只是語法糖的文章。在本文中,我想談談二元算術運算。
具體來說,我想解讀減法的工作原理:a - b。我故意選擇了減法,因為它是不可交換的。這可以強調出操作順序的重要性,與加法操作相比,你可能會在實現時誤將 a 和 b 翻轉,但還是得到相同的結果。
查看 C 代碼
按照慣例,我們從查看 CPython 解釋器編譯的字節碼開始。
>>> def sub(): a - b ... >>> import dis >>> dis.dis(sub) 1 0 LOAD_GLOBAL 0 (a) 2 LOAD_GLOBAL 1 (b) 4 BINARY_SUBTRACT 6 POP_TOP 8 LOAD_CONST 0 (None) 10 RETURN_VALUE
看起來我們需要深入研究 BINARY_SUBTRACT 操作碼。翻查 Python/ceval.c 文件,可以看到實現該操作碼的 C 代碼如下:
case TARGET(BINARY_SUBTRACT): { PyObject *right = POP(); PyObject *left = TOP(); PyObject *diff = PyNumber_Subtract(left, right); Py_DECREF(right); Py_DECREF(left); SET_TOP(diff); if (diff == NULL) goto error; DISPATCH(); }
來源:https://github.com/python/cpython/blob/6f8c8320e9eac9bc7a7f653b43506e75916ce8e8/Python/ceval.c#L1569-L1579
這里的關鍵代碼是PyNumber_Subtract(),實現了減法的實際語義。繼續查看該函數的一些宏,可以找到binary_op1() 函數。它提供了一種管理二元操作的通用方法。
不過,我們不把它作為實現的參考,而是要用Python的數據模型,官方文檔很好,清楚介紹了減法所使用的語義。
從數據模型中學習
通讀數據模型的文檔,你會發現在實現減法時,有兩個方法起到了關鍵作用:__sub__ 和 __rsub__。
1、__sub__()方法
當執行a - b 時,會在 a 的類型中查找__sub__(),然后把 b 作為它的參數。這很像我寫屬性訪問的文章 里的__getattribute__(),特殊/魔術方法是根據對象的類型來解析的,并不是出于性能目的而解析對象本身;在下面的示例代碼中,我使用_mro_getattr() 表示此過程。
因此,如果已定義 __sub__(),則 type(a).__sub__(a,b) 會被用來作減法操作。(譯注:魔術方法屬于對象的類型,不屬于對象)
這意味著在本質上,減法只是一個方法調用!你也可以將它理解成標準庫中的 operator.sub() 函數。
我們將仿造該函數實現自己的模型,用 lhs 和 rhs 兩個名稱,分別表示 a-b 的左側和右側,以使示例代碼更易于理解。
# 通過調用__sub__()實現減法 def sub(lhs: Any, rhs: Any, /) -> Any: """Implement the binary operation `a - b`.""" lhs_type = type(lhs) try: subtract = _mro_getattr(lhs_type, "__sub__") except AttributeError: msg = f"unsupported operand type(s) for -: {lhs_type!r} and {type(rhs)!r}" raise TypeError(msg) else: return subtract(lhs, rhs)
2、讓右側使用__rsub__()
但是,如果 a 沒有實現__sub__() 怎么辦?如果 a 和 b 是不同的類型,那么我們會嘗試調用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,代表在操作符的右側)。
當操作的雙方是不同類型時,這樣可以確保它們都有機會嘗試使表達式生效。當它們相同時,我們假設__sub__() 就能夠處理好。但是,即使兩邊的實現相同,你仍然要調用__rsub__(),以防其中一個對象是其它的(子)類。
3、不關心類型
現在,表達式雙方都可以參與運算!但是,如果由于某種原因,某個對象的類型不支持減法怎么辦(例如不支持 4 - “stuff”)?在這種情況下,__sub__ 或__rsub__ 能做的就是返回 NotImplemented。
這是給 Python 返回的信號,它應該繼續執行下一個操作,嘗試使代碼正常運行。對于我們的代碼,這意味著需要先檢查方法的返回值,然后才能假定它起作用。
# 減法的實現,其中表達式的左側和右側均可參與運算 _MISSING = object() def sub(lhs: Any, rhs: Any, /) -> Any: # lhs.__sub__ lhs_type = type(lhs) try: lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__") except AttributeError: lhs_method = _MISSING # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first) try: lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__") except AttributeError: lhs_rmethod = _MISSING # rhs.__rsub__ rhs_type = type(rhs) try: rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__") except AttributeError: rhs_method = _MISSING call_lhs = lhs, lhs_method, rhs call_rhs = rhs, rhs_method, lhs if lhs_type is not rhs_type: calls = call_lhs, call_rhs else: calls = (call_lhs,) for first_obj, meth, second_obj in calls: if meth is _MISSING: continue value = meth(first_obj, second_obj) if value is not NotImplemented: return value else: raise TypeError( f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}" )
4、子類優先于父類
如果你看一下__rsub__() 的文檔,就會注意到一條注釋。它說如果一個減法表達式的右側是左側的子類(真正的子類,同一類的不算),并且兩個對象的__rsub__() 方法不同,則在調用__sub__() 之前會先調用__rsub__()。換句話說,如果 b 是 a 的子類,調用的順序就會被顛倒。
這似乎是一個很奇怪的特例,但它背后是有原因的。當你創建一個子類時,這意味著你要在父類提供的操作上注入新的邏輯。這種邏輯不一定要加給父類,否則父類在對子類操作時,就很容易覆蓋子類想要實現的操作。
具體來說,假設有一個名為 Spam 的類,當你執行 Spam() - Spam() 時,得到一個 LessSpam 的實例。接著你又創建了一個 Spam 的子類名為 Bacon,這樣,當你用 Spam 去減 Bacon 時,你得到的是 VeggieSpam。
如果沒有上述規則,Spam() - Bacon() 將得到 LessSpam,因為 Spam 不知道減掉 Bacon 應該得出 VeggieSpam。
但是,有了上述規則,就會得到預期的結果 VeggieSpam,因為 Bacon.__rsub__() 首先會在表達式中被調用(如果計算的是 Bacon() - Spam(),那么也會得到正確的結果,因為首先會調用 Bacon.__sub__(),因此,規則里才會說兩個類的不同的方法需有區別,而不僅僅是一個由 issubclass() 判斷出的子類。)
# Python中減法的完整實現 _MISSING = object() def sub(lhs: Any, rhs: Any, /) -> Any: # lhs.__sub__ lhs_type = type(lhs) try: lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__") except AttributeError: lhs_method = _MISSING # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first) try: lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__") except AttributeError: lhs_rmethod = _MISSING # rhs.__rsub__ rhs_type = type(rhs) try: rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__") except AttributeError: rhs_method = _MISSING call_lhs = lhs, lhs_method, rhs call_rhs = rhs, rhs_method, lhs if ( rhs_type is not _MISSING # Do we care? and rhs_type is not lhs_type # Could RHS be a subclass? and issubclass(rhs_type, lhs_type) # RHS is a subclass! and lhs_rmethod is not rhs_method # Is __r*__ actually different? ): calls = call_rhs, call_lhs elif lhs_type is not rhs_type: calls = call_lhs, call_rhs else: calls = (call_lhs,) for first_obj, meth, second_obj in calls: if meth is _MISSING: continue value = meth(first_obj, second_obj) if value is not NotImplemented: return value else: raise TypeError( f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}" )
推廣到其它二元運算
解決掉了減法運算,那么其它二元運算又如何呢?好吧,事實證明它們的操作相同,只是碰巧使用了不同的特殊/魔術方法名稱。
所以,如果我們可以推廣這種方法,那么我們就可以實現 13 種操作的語義:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。
由于閉包和 Python 在對象自省上的靈活性,我們可以提煉出 operator 函數的創建。
# 一個創建閉包的函數,實現了二元運算的邏輯 _MISSING = object() def _create_binary_op(name: str, operator: str) -> Any: """Create a binary operation function. The `name` parameter specifies the name of the special method used for the binary operation (e.g. `sub` for `__sub__`). The `operator` name is the token representing the binary operation (e.g. `-` for subtraction). """ lhs_method_name = f"__{name}__" def binary_op(lhs: Any, rhs: Any, /) -> Any: """A closure implementing a binary operation in Python.""" rhs_method_name = f"__r{name}__" # lhs.__*__ lhs_type = type(lhs) try: lhs_method = debuiltins._mro_getattr(lhs_type, lhs_method_name) except AttributeError: lhs_method = _MISSING # lhs.__r*__ (for knowing if rhs.__r*__ should be called first) try: lhs_rmethod = debuiltins._mro_getattr(lhs_type, rhs_method_name) except AttributeError: lhs_rmethod = _MISSING # rhs.__r*__ rhs_type = type(rhs) try: rhs_method = debuiltins._mro_getattr(rhs_type, rhs_method_name) except AttributeError: rhs_method = _MISSING call_lhs = lhs, lhs_method, rhs call_rhs = rhs, rhs_method, lhs if ( rhs_type is not _MISSING # Do we care? and rhs_type is not lhs_type # Could RHS be a subclass? and issubclass(rhs_type, lhs_type) # RHS is a subclass! and lhs_rmethod is not rhs_method # Is __r*__ actually different? ): calls = call_rhs, call_lhs elif lhs_type is not rhs_type: calls = call_lhs, call_rhs else: calls = (call_lhs,) for first_obj, meth, second_obj in calls: if meth is _MISSING: continue value = meth(first_obj, second_obj) if value is not NotImplemented: return value else: exc = TypeError( f"unsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r}" ) exc._binary_op = operator raise exc
有了這段代碼,你可以將減法運算定義為 _create_binary_op(“sub”, “-”),然后根據需要重復定義出其它運算。
更多信息
通過本博客的“語法糖”標簽,你可以找到更多詳解 Python 語法的文章。
更正
數據分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
解碼數據基因:從數字敏感度到邏輯思維 每當看到超市貨架上商品的排列變化,你是否會聯想到背后的銷售數據波動?三年前在零售行 ...
2025-05-23在本文中,我們將探討 AI 為何能夠加速數據分析、如何在每個步驟中實現數據分析自動化以及使用哪些工具。 數據分析中的AI是什么 ...
2025-05-20當數據遇見人生:我的第一個分析項目 記得三年前接手第一個數據分析項目時,我面對Excel里密密麻麻的銷售數據手足無措。那些跳動 ...
2025-05-20在數字化運營的時代,企業每天都在產生海量數據:用戶點擊行為、商品銷售記錄、廣告投放反饋…… 這些數據就像散落的拼圖,而相 ...
2025-05-19在當今數字化營銷時代,小紅書作為國內領先的社交電商平臺,其銷售數據蘊含著巨大的商業價值。通過對小紅書銷售數據的深入分析, ...
2025-05-16Excel作為最常用的數據分析工具,有沒有什么工具可以幫助我們快速地使用excel表格,只要輕松幾步甚至輸入幾項指令就能搞定呢? ...
2025-05-15數據,如同無形的燃料,驅動著現代社會的運轉。從全球互聯網用戶每天產生的2.5億TB數據,到制造業的傳感器、金融交易 ...
2025-05-15大數據是什么_數據分析師培訓 其實,現在的大數據指的并不僅僅是海量數據,更準確而言是對大數據分析的方法。傳統的數 ...
2025-05-14CDA持證人簡介: 萬木,CDA L1持證人,某電商中廠BI工程師 ,5年數據經驗1年BI內訓師,高級數據分析師,擁有豐富的行業經驗。 ...
2025-05-13CDA持證人簡介: 王明月 ,CDA 數據分析師二級持證人,2年數據產品工作經驗,管理學博士在讀。 學習入口:https://edu.cda.cn/g ...
2025-05-12CDA持證人簡介: 楊貞璽 ,CDA一級持證人,鄭州大學情報學碩士研究生,某上市公司數據分析師。 學習入口:https://edu.cda.cn/g ...
2025-05-09CDA持證人簡介 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度、美團、阿里等 ...
2025-05-07相信很多做數據分析的小伙伴,都接到過一些高階的數據分析需求,實現的過程需要用到一些數據獲取,數據清洗轉換,建模方法等,這 ...
2025-05-06以下的文章內容來源于劉靜老師的專欄,如果您想閱讀專欄《10大業務分析模型突破業務瓶頸》,點擊下方鏈接 https://edu.cda.cn/g ...
2025-04-30CDA持證人簡介: 邱立峰 CDA 數據分析師二級持證人,數字化轉型專家,數據治理專家,高級數據分析師,擁有豐富的行業經驗。 ...
2025-04-29CDA持證人簡介: 程靖 CDA會員大咖,暢銷書《小白學產品》作者,13年頂級互聯網公司產品經理相關經驗,曾在百度,美團,阿里等 ...
2025-04-28CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-27數據分析在當今信息時代發揮著重要作用。單因素方差分析(One-Way ANOVA)是一種關鍵的統計方法,用于比較三個或更多獨立樣本組 ...
2025-04-25CDA持證人簡介: 居瑜 ,CDA一級持證人國企財務經理,13年財務管理運營經驗,在數據分析就業和實踐經驗方面有著豐富的積累和經 ...
2025-04-25在當今數字化時代,數據分析師的重要性與日俱增。但許多人在踏上這條職業道路時,往往充滿疑惑: 如何成為一名數據分析師?成為 ...
2025-04-24