查看 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();}

这里的要害代码是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 常识欢送返回公众号:Python 编程学习圈 ,发送 “J” 即可收费获取,每日干货分享