成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

詳解 Python 的二元算術運算,為什么說減法只是語法糖?

開發 后端
大家對我解讀屬性訪問的博客文章反應熱烈,這啟發了我再寫一篇關于 Python 有多少語法實際上只是語法糖的文章。在本文中,我想談談二元算術運算。

[[341459]]

大家對我解讀屬性訪問的博客文章反應熱烈,這啟發了我再寫一篇關于 Python 有多少語法實際上只是語法糖的文章。在本文中,我想談談二元算術運算。

具體來說,我想解讀減法的工作原理:a - b。我故意選擇了減法,因為它是不可交換的。這可以強調出操作順序的重要性,與加法操作相比,你可能會在實現時誤將 a 和 b 翻轉,但還是得到相同的結果。

查看 C 代碼

按照慣例,我們從查看 CPython 解釋器編譯的字節碼開始。

  1. >>> def sub(): a - b 
  2. ...  
  3. >>> import dis 
  4. >>> dis.dis(sub) 
  5.   1           0 LOAD_GLOBAL              0 (a) 
  6.               2 LOAD_GLOBAL              1 (b) 
  7.               4 BINARY_SUBTRACT 
  8.               6 POP_TOP 
  9.               8 LOAD_CONST               0 (None) 
  10.              10 RETURN_VALUE 

看起來我們需要深入研究 BINARY_SUBTRACT 操作碼。翻查 Python/ceval.c 文件,可以看到實現該操作碼的 C 代碼如下:

  1. case TARGET(BINARY_SUBTRACT): { 
  2.     PyObject *right = POP(); 
  3.     PyObject *left = TOP(); 
  4.     PyObject *diff = PyNumber_Subtract(leftright); 
  5.     Py_DECREF(right); 
  6.     Py_DECREF(left); 
  7.     SET_TOP(diff); 
  8.     if (diff == NULL
  9.     goto error; 
  10.     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 的左側和右側,以使示例代碼更易于理解。

  1. # 通過調用__sub__()實現減法  
  2. def sub(lhs: Any, rhs: Any, /) -> Any
  3.     """Implement the binary operation `a - b`.""" 
  4.     lhs_type = type(lhs) 
  5.     try: 
  6.         subtract = _mro_getattr(lhs_type, "__sub__"
  7.     except AttributeError: 
  8.         msg = f"unsupported operand type(s) for -: {lhs_type!r} and {type(rhs)!r}" 
  9.         raise TypeError(msg) 
  10.     else
  11.         return subtract(lhs, rhs) 

2、讓右側使用__rsub__()

但是,如果 a 沒有實現__sub__() 怎么辦?如果 a 和 b 是不同的類型,那么我們會嘗試調用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,代表在操作符的右側)。

當操作的雙方是不同類型時,這樣可以確保它們都有機會嘗試使表達式生效。當它們相同時,我們假設__sub__() 就能夠處理好。但是,即使兩邊的實現相同,你仍然要調用__rsub__(),以防其中一個對象是其它的(子)類。

3、不關心類型

現在,表達式雙方都可以參與運算!但是,如果由于某種原因,某個對象的類型不支持減法怎么辦(例如不支持 4 - “stuff”)?在這種情況下,__sub__ 或__rsub__ 能做的就是返回 NotImplemented。

這是給 Python 返回的信號,它應該繼續執行下一個操作,嘗試使代碼正常運行。對于我們的代碼,這意味著需要先檢查方法的返回值,然后才能假定它起作用。

  1. # 減法的實現,其中表達式的左側和右側均可參與運算 
  2. _MISSING = object() 
  3.  
  4. def sub(lhs: Any, rhs: Any, /) -> Any
  5.         # lhs.__sub__ 
  6.         lhs_type = type(lhs) 
  7.         try: 
  8.             lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__"
  9.         except AttributeError: 
  10.             lhs_method = _MISSING 
  11.  
  12.         # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first
  13.         try: 
  14.             lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__"
  15.         except AttributeError: 
  16.             lhs_rmethod = _MISSING 
  17.  
  18.         # rhs.__rsub__ 
  19.         rhs_type = type(rhs) 
  20.         try: 
  21.             rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__"
  22.         except AttributeError: 
  23.             rhs_method = _MISSING 
  24.  
  25.         call_lhs = lhs, lhs_method, rhs 
  26.         call_rhs = rhs, rhs_method, lhs 
  27.  
  28.         if lhs_type is not rhs_type: 
  29.             calls = call_lhs, call_rhs 
  30.         else
  31.             calls = (call_lhs,) 
  32.  
  33.         for first_obj, meth, second_obj in calls: 
  34.             if meth is _MISSING: 
  35.                 continue 
  36.             value = meth(first_obj, second_obj) 
  37.             if value is not NotImplemented: 
  38.                 return value 
  39.         else
  40.             raise TypeError( 
  41.                 f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}" 
  42.             ) 

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() 判斷出的子類。)

  1. # Python中減法的完整實現 
  2. _MISSING = object() 
  3.  
  4. def sub(lhs: Any, rhs: Any, /) -> Any
  5.         # lhs.__sub__ 
  6.         lhs_type = type(lhs) 
  7.         try: 
  8.             lhs_method = debuiltins._mro_getattr(lhs_type, "__sub__"
  9.         except AttributeError: 
  10.             lhs_method = _MISSING 
  11.  
  12.         # lhs.__rsub__ (for knowing if rhs.__rub__ should be called first
  13.         try: 
  14.             lhs_rmethod = debuiltins._mro_getattr(lhs_type, "__rsub__"
  15.         except AttributeError: 
  16.             lhs_rmethod = _MISSING 
  17.  
  18.         # rhs.__rsub__ 
  19.         rhs_type = type(rhs) 
  20.         try: 
  21.             rhs_method = debuiltins._mro_getattr(rhs_type, "__rsub__"
  22.         except AttributeError: 
  23.             rhs_method = _MISSING 
  24.  
  25.         call_lhs = lhs, lhs_method, rhs 
  26.         call_rhs = rhs, rhs_method, lhs 
  27.  
  28.         if ( 
  29.             rhs_type is not _MISSING  # Do we care? 
  30.             and rhs_type is not lhs_type  # Could RHS be a subclass? 
  31.             and issubclass(rhs_type, lhs_type)  # RHS is a subclass! 
  32.             and lhs_rmethod is not rhs_method  # Is __r*__ actually different? 
  33.         ): 
  34.             calls = call_rhs, call_lhs 
  35.         elif lhs_type is not rhs_type: 
  36.             calls = call_lhs, call_rhs 
  37.         else
  38.             calls = (call_lhs,) 
  39.  
  40.         for first_obj, meth, second_obj in calls: 
  41.             if meth is _MISSING: 
  42.                 continue 
  43.             value = meth(first_obj, second_obj) 
  44.             if value is not NotImplemented: 
  45.                 return value 
  46.         else
  47.             raise TypeError( 
  48.                 f"unsupported operand type(s) for -: {lhs_type!r} and {rhs_type!r}" 
  49.             ) 

推廣到其它二元運算

解決掉了減法運算,那么其它二元運算又如何呢?好吧,事實證明它們的操作相同,只是碰巧使用了不同的特殊/魔術方法名稱。

所以,如果我們可以推廣這種方法,那么我們就可以實現 13 種操作的語義:+ 、-、*、@、/、//、%、**、<<、>>、&、^、和 |。

由于閉包和 Python 在對象自省上的靈活性,我們可以提煉出 operator 函數的創建。

  1. # 一個創建閉包的函數,實現了二元運算的邏輯 
  2. _MISSING = object() 
  3.  
  4.  
  5. def _create_binary_op(name: str, operator: str) -> Any
  6.     """Create a binary operation function
  7.  
  8.     The `name` parameter specifies the name of the special method used for the 
  9.     binary operation (e.g. `sub` for `__sub__`). The `operator` name is the 
  10.     token representing the binary operation (e.g. `-` for subtraction). 
  11.  
  12.     ""
  13.  
  14.     lhs_method_name = f"__{name}__" 
  15.  
  16.     def binary_op(lhs: Any, rhs: Any, /) -> Any
  17.         """A closure implementing a binary operation in Python.""" 
  18.         rhs_method_name = f"__r{name}__" 
  19.  
  20.         # lhs.__*__ 
  21.         lhs_type = type(lhs) 
  22.         try: 
  23.             lhs_method = debuiltins._mro_getattr(lhs_type, lhs_method_name) 
  24.         except AttributeError: 
  25.             lhs_method = _MISSING 
  26.  
  27.         # lhs.__r*__ (for knowing if rhs.__r*__ should be called first
  28.         try: 
  29.             lhs_rmethod = debuiltins._mro_getattr(lhs_type, rhs_method_name) 
  30.         except AttributeError: 
  31.             lhs_rmethod = _MISSING 
  32.  
  33.         # rhs.__r*__ 
  34.         rhs_type = type(rhs) 
  35.         try: 
  36.             rhs_method = debuiltins._mro_getattr(rhs_type, rhs_method_name) 
  37.         except AttributeError: 
  38.             rhs_method = _MISSING 
  39.  
  40.         call_lhs = lhs, lhs_method, rhs 
  41.         call_rhs = rhs, rhs_method, lhs 
  42.  
  43.         if ( 
  44.             rhs_type is not _MISSING  # Do we care? 
  45.             and rhs_type is not lhs_type  # Could RHS be a subclass? 
  46.             and issubclass(rhs_type, lhs_type)  # RHS is a subclass! 
  47.             and lhs_rmethod is not rhs_method  # Is __r*__ actually different? 
  48.         ): 
  49.             calls = call_rhs, call_lhs 
  50.         elif lhs_type is not rhs_type: 
  51.             calls = call_lhs, call_rhs 
  52.         else
  53.             calls = (call_lhs,) 
  54.  
  55.         for first_obj, meth, second_obj in calls: 
  56.             if meth is _MISSING: 
  57.                 continue 
  58.             value = meth(first_obj, second_obj) 
  59.             if value is not NotImplemented: 
  60.                 return value 
  61.         else
  62.             exc = TypeError( 
  63.                 f"unsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r}" 
  64.             ) 
  65.             exc._binary_op = operator 
  66.             raise exc 

有了這段代碼,你可以將減法運算定義為 _create_binary_op(“sub”, “-”),然后根據需要重復定義出其它運算。

更多信息

通過本博客的“語法糖”標簽,你可以找到更多詳解 Python 語法的文章。源代碼可以在 https://github.com/brettcannon/desugar 上找到。

更正2020-08-19:修復了當__rsub__() 比 __sub__() 先調用時的規則。

2020-08-22:修復了當類型相同時不調用__rsub__ 的問題;還精簡了過渡代碼,僅保留開頭和結尾代碼,這讓我輕松些。

 

2020-08-23:在多數示例中添加了內容。

原題 | Unravelling binary arithmetic operations in Python

作者 | Brett Cannon

譯者 | 豌豆花下貓(“Python貓”公眾號作者)

 

聲明 | 本翻譯是出于交流學習的目的,基于 CC BY-NC-SA 4.0 授權協議。為便于閱讀,內容略有改動。

本文轉載自微信公眾號「 Python貓」,可以通過以下二維碼關注。轉載本文請聯系 Python貓公眾號。

 

責任編輯:武曉燕 來源: Python貓
相關推薦

2025-03-17 09:00:00

C++引用編程

2016-10-14 14:04:34

JAVA語法main

2016-06-02 15:10:12

SwiftSelector

2022-10-08 06:38:01

元宇宙NFT加密貨幣

2020-12-08 07:51:53

Java語法糖泛型

2024-10-09 08:00:00

2010-03-09 11:15:28

Python語言教程

2022-02-14 08:04:02

Go語法糖編譯器

2022-04-10 22:59:51

區塊鏈元宇宙技術

2009-06-02 17:05:19

網管運維管理摩卡軟件

2012-01-05 10:31:17

Kindle Fire

2024-03-15 08:45:31

Vue 3setup語法

2020-12-20 17:37:38

Java開發代碼

2011-11-08 09:18:42

云計算開源OpenStack

2020-07-22 08:01:41

Python開發運算符

2024-09-11 16:34:38

語法糖Java語言

2022-05-20 11:41:00

數據科學編程語言Python

2022-03-14 08:33:09

TypeScriptJavaScript前端

2020-07-03 14:05:26

Serverless云服務商

2021-11-29 18:27:12

Web Wasmjs
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 日韩欧美专区 | 国产一区 | 中文字幕精品一区二区三区精品 | 中文字幕一区在线观看视频 | 亚洲成人久久久 | 99精品久久久国产一区二区三 | 伦理二区| 日韩成人av在线 | 亚洲视频在线观看 | 丁香一区二区 | 久久久久久久久蜜桃 | 特黄毛片 | 午夜激情免费 | 亚洲精品二区 | 国产精品久久久久久久久久 | 亚洲美女视频 | 青青久久av北条麻妃海外网 | 欧美精品黄 | 欧美一区二区三区久久精品 | 操一草| 亚洲欧美一区二区三区国产精品 | 日日夜夜狠狠操 | 久久久精品一区二区三区 | 亚洲精品久久久一区二区三区 | 在线视频成人 | 久久爱黑人激情av摘花 | 国产成人在线播放 | 欧美日韩国产高清视频 | 一区二区成人 | 久久精品国产一区二区电影 | 欧美综合久久 | 激情 一区 | 涩涩片影院 | 免费在线观看一级毛片 | 精品国产一区二区 | 中文字幕精品一区久久久久 | 欧美一区二区三区在线观看 | 日本精品一区 | 欧美日韩综合视频 | 亚洲欧美日韩精品久久亚洲区 | 色婷婷影院|