Python 的二元算术运算详解-Python教程

资源魔 44 0

相干学习保举: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__。

一、__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)复制代码

二、让右侧应用__rsub__()

然而,假如 a 不完成__sub__() 怎样办?假如 a 以及 b 是没有同的类型,那末咱们会测验考试挪用 b 的 __rsub__()(__rsub__ 外面的“r”示意“右”,代表正在操作符的右侧)。

当操作的单方是没有同类型时,这样能够确保它们都无机会测验考试使表白式失效。当它们相反时,咱们假定__sub__() 就可以解决好。然而,即便两边的完成相反,你依然要挪用__rsub__(),以防此中一个工具是其它的(子)类。

三、没有关怀类型

如今,表白式单方均可以参加运算!然而,假如因为某种缘由,某个工具的类型没有支持减法怎样办(例如没有支持 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}"
            )复制代码

四、子类优先于父类

假如你看一下__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 的二元算术运算详解的具体内容,更多请存眷资源魔其它相干文章!

标签: Python python教程 python编程 python使用问题 二元算术

抱歉,评论功能暂时关闭!