欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Python二元算術(shù)運(yùn)算常用方法解析

 更新時(shí)間:2020年09月15日 09:39:21   作者:小幾斤  
這篇文章主要介紹了Python二元算術(shù)運(yùn)算常用方法解析,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下

在本文中,我想談?wù)劧阈g(shù)運(yùn)算。具體來說,我想解讀減法的工作原理:a - b。我故意選擇了減法,因?yàn)樗遣豢山粨Q的。這可以強(qiáng)調(diào)出操作順序的重要性,與加法操作相比,你可能會在實(shí)現(xiàn)時(shí)誤將 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 文件,可以看到實(shí)現(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(),實(shí)現(xiàn)了減法的實(shí)際語義。繼續(xù)查看該函數(shù)的一些宏,可以找到binary_op1() 函數(shù)。它提供了一種管理二元操作的通用方法。

不過,我們不把它作為實(shí)現(xiàn)的參考,而是要用Python的數(shù)據(jù)模型,官方文檔很好,清楚介紹了減法所使用的語義。

從數(shù)據(jù)模型中學(xué)習(xí)

通讀數(shù)據(jù)模型的文檔,你會發(fā)現(xiàn)在實(shí)現(xiàn)減法時(shí),有兩個(gè)方法起到了關(guān)鍵作用:__sub__ 和 __rsub__。

1、__sub__()方法

當(dāng)執(zhí)行a - b 時(shí),會在 a 的類型中查找__sub__(),然后把 b 作為它的參數(shù)。這很像我寫屬性訪問的文章 里的__getattribute__(),特殊/魔術(shù)方法是根據(jù)對象的類型來解析的,并不是出于性能目的而解析對象本身;在下面的示例代碼中,我使用_mro_getattr() 表示此過程。

因此,如果已定義 __sub__(),則 type(a).__sub__(a,b) 會被用來作減法操作。(譯注:魔術(shù)方法屬于對象的類型,不屬于對象)

這意味著在本質(zhì)上,減法只是一個(gè)方法調(diào)用!你也可以將它理解成標(biāo)準(zhǔn)庫中的 operator.sub() 函數(shù)。

我們將仿造該函數(shù)實(shí)現(xiàn)自己的模型,用 lhs 和 rhs 兩個(gè)名稱,分別表示 a-b 的左側(cè)和右側(cè),以使示例代碼更易于理解。

# 通過調(diào)用__sub__()實(shí)現(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 沒有實(shí)現(xiàn)__sub__() 怎么辦?如果 a 和 b 是不同的類型,那么我們會嘗試調(diào)用 b 的 __rsub__()(__rsub__ 里面的“r”表示“右”,代表在操作符的右側(cè))。

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

3、不關(guān)心類型

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

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

# 減法的實(shí)現(xiàn),其中表達(dá)式的左側(cè)和右側(cè)均可參與運(yù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 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__() 的文檔,就會注意到一條注釋。它說如果一個(gè)減法表達(dá)式的右側(cè)是左側(cè)的子類(真正的子類,同一類的不算),并且兩個(gè)對象的__rsub__() 方法不同,則在調(diào)用__sub__() 之前會先調(diào)用__rsub__()。換句話說,如果 b 是 a 的子類,調(diào)用的順序就會被顛倒。

這似乎是一個(gè)很奇怪的特例,但它背后是有原因的。當(dāng)你創(chuàng)建一個(gè)子類時(shí),這意味著你要在父類提供的操作上注入新的邏輯。這種邏輯不一定要加給父類,否則父類在對子類操作時(shí),就很容易覆蓋子類想要實(shí)現(xiàn)的操作。

具體來說,假設(shè)有一個(gè)名為 Spam 的類,當(dāng)你執(zhí)行 Spam() - Spam() 時(shí),得到一個(gè) LessSpam 的實(shí)例。接著你又創(chuàng)建了一個(gè) Spam 的子類名為 Bacon,這樣,當(dāng)你用 Spam 去減 Bacon 時(shí),你得到的是 VeggieSpam。

如果沒有上述規(guī)則,Spam() - Bacon() 將得到 LessSpam,因?yàn)?Spam 不知道減掉 Bacon 應(yīng)該得出 VeggieSpam。

但是,有了上述規(guī)則,就會得到預(yù)期的結(jié)果 VeggieSpam,因?yàn)?Bacon.__rsub__() 首先會在表達(dá)式中被調(diào)用(如果計(jì)算的是 Bacon() - Spam(),那么也會得到正確的結(jié)果,因?yàn)槭紫葧{(diào)用 Bacon.__sub__(),因此,規(guī)則里才會說兩個(gè)類的不同的方法需有區(qū)別,而不僅僅是一個(gè)由 issubclass() 判斷出的子類。)

# Python中減法的完整實(shí)現(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}" 
      )

推廣到其它二元運(yùn)算

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

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

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

# 一個(gè)創(chuàng)建閉包的函數(shù),實(shí)現(xiàn)了二元運(yù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

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

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • 2020最新pycharm漢化安裝(python工程獅親測有效)

    2020最新pycharm漢化安裝(python工程獅親測有效)

    這篇文章主要介紹了2020最新pycharm漢化安裝(python工程獅親測有效),文中通過圖文介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2020-04-04
  • python學(xué)生管理系統(tǒng)的實(shí)現(xiàn)

    python學(xué)生管理系統(tǒng)的實(shí)現(xiàn)

    這篇文章主要為大家詳細(xì)介紹了python學(xué)生管理系統(tǒng)的實(shí)現(xiàn),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
    2020-04-04
  • 詳解如何使用python打印出多樣字符

    詳解如何使用python打印出多樣字符

    當(dāng)你第一次進(jìn)入Python的世界里,學(xué)到的第一句代碼是不是print("Hello?World"),今天,讓我們一起來開啟探索print()的奇妙之旅,從最基礎(chǔ)的打印字符用法到讓它跳舞唱歌——?jiǎng)討B(tài)顯示,讓我們一步步解鎖print()的各種技能吧,需要的朋友可以參考下
    2024-03-03
  • pytorch模型訓(xùn)練的時(shí)候GPU使用率不高的問題

    pytorch模型訓(xùn)練的時(shí)候GPU使用率不高的問題

    這篇文章主要介紹了pytorch模型訓(xùn)練的時(shí)候GPU使用率不高的問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-09-09
  • Python數(shù)值求解微分方程方法(歐拉法,隱式歐拉)

    Python數(shù)值求解微分方程方法(歐拉法,隱式歐拉)

    這篇文章主要介紹了Python數(shù)值求解微分方程方法(歐拉法,隱式歐拉),文章圍繞主題展開詳細(xì)的內(nèi)介紹,具有一定的參考價(jià)值,需要的小伙伴可以參考一下
    2022-09-09
  • Python中在for循環(huán)中嵌套使用if和else語句的技巧

    Python中在for循環(huán)中嵌套使用if和else語句的技巧

    Python的語法糖非常強(qiáng)大,比如Python中在for循環(huán)中嵌套使用if和else語句的技巧便十分給力,下面我們就舉幾個(gè)例子來看詳細(xì)的用法:
    2016-06-06
  • python?ast模塊詳析與用法

    python?ast模塊詳析與用法

    這篇文章主要給大家介紹了關(guān)于python?ast模塊詳析與用法的相關(guān)資料, Python的ast(Abstract Syntax Trees,抽象語法樹)模塊是一個(gè)內(nèi)置模塊,用于解析Python代碼并生成語法樹,需要的朋友可以參考下
    2023-07-07
  • Pytorch.nn.conv2d 過程驗(yàn)證方式(單,多通道卷積過程)

    Pytorch.nn.conv2d 過程驗(yàn)證方式(單,多通道卷積過程)

    今天小編就為大家分享一篇Pytorch.nn.conv2d 過程驗(yàn)證方式(單,多通道卷積過程),具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-01-01
  • python妙用之編碼的轉(zhuǎn)換詳解

    python妙用之編碼的轉(zhuǎn)換詳解

    在日常滲透,漏洞挖掘,甚至是CTF比賽中會遇到各種編碼,常常伴隨著這些編碼之間的各種轉(zhuǎn)換。下面這篇文章主要介紹了python中編碼轉(zhuǎn)換妙用的相關(guān)資料,需要的朋友們可以參考借鑒,下面來一起看看吧。
    2017-04-04
  • numpy和tensorflow中的各種乘法(點(diǎn)乘和矩陣乘)

    numpy和tensorflow中的各種乘法(點(diǎn)乘和矩陣乘)

    這篇文章主要介紹了numpy和tensorflow中的各種乘法(點(diǎn)乘和矩陣乘),文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧
    2021-03-03

最新評論