首頁  >  文章  >  後端開發  >  Python 的二元算術運算詳解

Python 的二元算術運算詳解

coldplay.xixi
coldplay.xixi轉載
2020-09-10 16:41:212443瀏覽

Python 的二元算術運算詳解

相關學習推薦:python教程

#大家對我解讀屬性訪問的部落格文章反應熱烈,這啟發了我再寫一篇關於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();
}复制代码

來源:github.com/python/cpyt…

這裡的關鍵程式碼是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”, “-”),然后根据需要重复定义出其它运算。

想了解更多编程学习,敬请关注php培训栏目!

以上是Python 的二元算術運算詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:juejin.im。如有侵權,請聯絡admin@php.cn刪除