
原題 | Unravelling binary arithmetic operations in Python
作者 | Brett Cannon
譯者 | 豌豆花下貓
來源 | Python貓
聲明 | 本翻譯是出于交流學習的目的,基于 CC BY-NC-SA 4.0 授權(quán)協(xié)議。為便于閱讀,內(nèi)容略有改動。
大家對我解讀屬性訪問的博客文章反應熱烈,這啟發(fā)了我再寫一篇關(guān)于 python 有多少語法實際上只是語法糖的文章。在本文中,我想談談二元算術(shù)運算。
具體來說,我想解讀減法的工作原理:a - b。我故意選擇了減法,因為它是不可交換的。這可以強調(diào)出操作順序的重要性,與加法操作相比,你可能會在實現(xiàn)時誤將 a 和 b 翻轉(zhuǎn),但還是得到相同的結(jié)果。
查看 C 代碼
按照慣例,我們從查看 CPython 解釋器編譯的字節(jié)碼開始。
>>> 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 文件,可以看到實現(xiàn)該操作碼的 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
這里的關(guān)鍵代碼是PyNumber_Subtract(),實現(xiàn)了減法的實際語義。繼續(xù)查看該函數(shù)的一些宏,可以找到binary_op1() 函數(shù)。它提供了一種管理二元操作的通用方法。
不過,我們不把它作為實現(xiàn)的參考,而是要用Python的數(shù)據(jù)模型,官方文檔很好,清楚介紹了減法所使用的語義。
從數(shù)據(jù)模型中學習
通讀數(shù)據(jù)模型的文檔,你會發(fā)現(xiàn)在實現(xiàn)減法時,有兩個方法起到了關(guān)鍵作用:__sub__ 和 __rsub__。
1、__sub__()方法
當執(zhí)行a - b 時,會在 a 的類型中查找__sub__(),然后把 b 作為它的參數(shù)。這很像我寫屬性訪問的文章 里的__getattribute__(),特殊/魔術(shù)方法是根據(jù)對象的類型來解析的,并不是出于性能目的而解析對象本身;在下面的示例代碼中,我使用_mro_getattr() 表示此過程。
因此,如果已定義 __sub__(),則 type(a).__sub__(a,b) 會被用來作減法操作。(譯注:魔術(shù)方法屬于對象的類型,不屬于對象)
這意味著在本質(zhì)上,減法只是一個方法調(diào)用!你也可以將它理解成標準庫中的 operator.sub() 函數(shù)。
我們將仿造該函數(shù)實現(xiàn)自己的模型,用 lhs 和 rhs 兩個名稱,分別表示 a-b 的左側(cè)和右側(cè),以使示例代碼更易于理解。
# 通過調(diào)用__sub__()實現(xiàn)減法 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、讓右側(cè)使用__rsub__()
但是,如果 a 沒有實現(xiàn)__sub__() 怎么辦?如果 a 和 b 是不同的類型,那么我們會嘗試調(diào)用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,代表在操作符的右側(cè))。
當操作的雙方是不同類型時,這樣可以確保它們都有機會嘗試使表達式生效。當它們相同時,我們假設__sub__() 就能夠處理好。但是,即使兩邊的實現(xiàn)相同,你仍然要調(diào)用__rsub__(),以防其中一個對象是其它的(子)類。
3、不關(guān)心類型
現(xiàn)在,表達式雙方都可以參與運算!但是,如果由于某種原因,某個對象的類型不支持減法怎么辦(例如不支持 4 - “stuff”)?在這種情況下,__sub__ 或__rsub__ 能做的就是返回 NotImplemented。
這是給 Python 返回的信號,它應該繼續(xù)執(zhí)行下一個操作,嘗試使代碼正常運行。對于我們的代碼,這意味著需要先檢查方法的返回值,然后才能假定它起作用。
# 減法的實現(xiàn),其中表達式的左側(cè)和右側(cè)均可參與運算 _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、子類優(yōu)先于父類
如果你看一下__rsub__() 的文檔,就會注意到一條注釋。它說如果一個減法表達式的右側(cè)是左側(cè)的子類(真正的子類,同一類的不算),并且兩個對象的__rsub__() 方法不同,則在調(diào)用__sub__() 之前會先調(diào)用__rsub__()。換句話說,如果 b 是 a 的子類,調(diào)用的順序就會被顛倒。
這似乎是一個很奇怪的特例,但它背后是有原因的。當你創(chuàng)建一個子類時,這意味著你要在父類提供的操作上注入新的邏輯。這種邏輯不一定要加給父類,否則父類在對子類操作時,就很容易覆蓋子類想要實現(xiàn)的操作。
具體來說,假設有一個名為 Spam 的類,當你執(zhí)行 Spam() - Spam() 時,得到一個 LessSpam 的實例。接著你又創(chuàng)建了一個 Spam 的子類名為 Bacon,這樣,當你用 Spam 去減 Bacon 時,你得到的是 VeggieSpam。
如果沒有上述規(guī)則,Spam() - Bacon() 將得到 LessSpam,因為 Spam 不知道減掉 Bacon 應該得出 VeggieSpam。
但是,有了上述規(guī)則,就會得到預期的結(jié)果 VeggieSpam,因為 Bacon.__rsub__() 首先會在表達式中被調(diào)用(如果計算的是 Bacon() - Spam(),那么也會得到正確的結(jié)果,因為首先會調(diào)用 Bacon.__sub__(),因此,規(guī)則里才會說兩個類的不同的方法需有區(qū)別,而不僅僅是一個由 issubclass() 判斷出的子類。)
# Python中減法的完整實現(xiàn) _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}" )
推廣到其它二元運算
解決掉了減法運算,那么其它二元運算又如何呢?好吧,事實證明它們的操作相同,只是碰巧使用了不同的特殊/魔術(shù)方法名稱。
所以,如果我們可以推廣這種方法,那么我們就可以實現(xiàn) 13 種操作的語義:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。
由于閉包和 Python 在對象自省上的靈活性,我們可以提煉出 operator 函數(shù)的創(chuàng)建。
# 一個創(chuàng)建閉包的函數(shù),實現(xiàn)了二元運算的邏輯 _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”, “-”),然后根據(jù)需要重復定義出其它運算。
更多信息
通過本博客的“語法糖”標簽,你可以找到更多詳解 Python 語法的文章。
更正
數(shù)據(jù)分析咨詢請掃描二維碼
若不方便掃碼,搜微信號:CDAshujufenxi
LSTM 模型輸入長度選擇技巧:提升序列建模效能的關(guān)鍵? 在循環(huán)神經(jīng)網(wǎng)絡(RNN)家族中,長短期記憶網(wǎng)絡(LSTM)憑借其解決長序列 ...
2025-07-11CDA 數(shù)據(jù)分析師報考條件詳解與準備指南? ? 在數(shù)據(jù)驅(qū)動決策的時代浪潮下,CDA 數(shù)據(jù)分析師認證愈發(fā)受到矚目,成為眾多有志投身數(shù) ...
2025-07-11數(shù)據(jù)透視表中兩列相乘合計的實用指南? 在數(shù)據(jù)分析的日常工作中,數(shù)據(jù)透視表憑借其強大的數(shù)據(jù)匯總和分析功能,成為了 Excel 用戶 ...
2025-07-11尊敬的考生: 您好! 我們誠摯通知您,CDA Level I和 Level II考試大綱將于 2025年7月25日 實施重大更新。 此次更新旨在確保認 ...
2025-07-10BI 大數(shù)據(jù)分析師:連接數(shù)據(jù)與業(yè)務的價值轉(zhuǎn)化者? ? 在大數(shù)據(jù)與商業(yè)智能(Business Intelligence,簡稱 BI)深度融合的時代,BI ...
2025-07-10SQL 在預測分析中的應用:從數(shù)據(jù)查詢到趨勢預判? ? 在數(shù)據(jù)驅(qū)動決策的時代,預測分析作為挖掘數(shù)據(jù)潛在價值的核心手段,正被廣泛 ...
2025-07-10數(shù)據(jù)查詢結(jié)束后:分析師的收尾工作與價值深化? ? 在數(shù)據(jù)分析的全流程中,“query end”(查詢結(jié)束)并非工作的終點,而是將數(shù) ...
2025-07-10CDA 數(shù)據(jù)分析師考試:從報考到取證的全攻略? 在數(shù)字經(jīng)濟蓬勃發(fā)展的今天,數(shù)據(jù)分析師已成為各行業(yè)爭搶的核心人才,而 CDA(Certi ...
2025-07-09【CDA干貨】單樣本趨勢性檢驗:捕捉數(shù)據(jù)背后的時間軌跡? 在數(shù)據(jù)分析的版圖中,單樣本趨勢性檢驗如同一位耐心的偵探,專注于從單 ...
2025-07-09year_month數(shù)據(jù)類型:時間維度的精準切片? ? 在數(shù)據(jù)的世界里,時間是最不可或缺的維度之一,而year_month數(shù)據(jù)類型就像一把精準 ...
2025-07-09CDA 備考干貨:Python 在數(shù)據(jù)分析中的核心應用與實戰(zhàn)技巧? ? 在 CDA 數(shù)據(jù)分析師認證考試中,Python 作為數(shù)據(jù)處理與分析的核心 ...
2025-07-08SPSS 中的 Mann-Kendall 檢驗:數(shù)據(jù)趨勢與突變分析的有力工具? ? ? 在數(shù)據(jù)分析的廣袤領(lǐng)域中,準確捕捉數(shù)據(jù)的趨勢變化以及識別 ...
2025-07-08備戰(zhàn) CDA 數(shù)據(jù)分析師考試:需要多久?如何規(guī)劃? CDA(Certified Data Analyst)數(shù)據(jù)分析師認證作為國內(nèi)權(quán)威的數(shù)據(jù)分析能力認證 ...
2025-07-08LSTM 輸出不確定的成因、影響與應對策略? 長短期記憶網(wǎng)絡(LSTM)作為循環(huán)神經(jīng)網(wǎng)絡(RNN)的一種變體,憑借獨特的門控機制,在 ...
2025-07-07統(tǒng)計學方法在市場調(diào)研數(shù)據(jù)中的深度應用? 市場調(diào)研是企業(yè)洞察市場動態(tài)、了解消費者需求的重要途徑,而統(tǒng)計學方法則是市場調(diào)研數(shù) ...
2025-07-07CDA數(shù)據(jù)分析師證書考試全攻略? 在數(shù)字化浪潮席卷全球的當下,數(shù)據(jù)已成為企業(yè)決策、行業(yè)發(fā)展的核心驅(qū)動力,數(shù)據(jù)分析師也因此成為 ...
2025-07-07剖析 CDA 數(shù)據(jù)分析師考試題型:解鎖高效備考與答題策略? CDA(Certified Data Analyst)數(shù)據(jù)分析師考試作為衡量數(shù)據(jù)專業(yè)能力的 ...
2025-07-04SQL Server 字符串截取轉(zhuǎn)日期:解鎖數(shù)據(jù)處理的關(guān)鍵技能? 在數(shù)據(jù)處理與分析工作中,數(shù)據(jù)格式的規(guī)范性是保證后續(xù)分析準確性的基礎 ...
2025-07-04CDA 數(shù)據(jù)分析師視角:從數(shù)據(jù)迷霧中探尋商業(yè)真相? 在數(shù)字化浪潮席卷全球的今天,數(shù)據(jù)已成為企業(yè)決策的核心驅(qū)動力,CDA(Certifie ...
2025-07-04CDA 數(shù)據(jù)分析師:開啟數(shù)據(jù)職業(yè)發(fā)展新征程? ? 在數(shù)據(jù)成為核心生產(chǎn)要素的今天,數(shù)據(jù)分析師的職業(yè)價值愈發(fā)凸顯。CDA(Certified D ...
2025-07-03