上海市建设部注册中心网站,各大网站地区是怎样和做的,网站免费部署,安阳网站设计多少钱原题 | Unravelling binary arithmetic operations in Python作者 | Brett Cannon译者 | 豌豆花下猫(“Python猫”公众号作者)声明 | 本翻译是出于交流学习的目的#xff0c;基于 CC BY-NC-SA 4.0 授权协议。为便于阅读#xff0c;内容略有改动。大家对我解读属性访问的博客文…原题 | Unravelling binary arithmetic operations in Python作者 | Brett Cannon译者 | 豌豆花下猫(“Python猫”公众号作者)声明 | 本翻译是出于交流学习的目的基于 CC BY-NC-SA 4.0 授权协议。为便于阅读内容略有改动。大家对我解读属性访问的博客文章反应热烈这启发了我再写一篇关于 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();}来源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 的左侧和右侧以使示例代码更易于理解。# 通过调用__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 funsupported 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( funsupported 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( funsupported 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( funsupported operand type(s) for {operator}: {lhs_type!r} and {rhs_type!r} ) exc._binary_op operator raise exc有了这段代码你可以将减法运算定义为 _create_binary_op(“sub”, “-”)然后根据需要重复定义出其它运算。更多信息通过本博客的“语法糖”标签你可以找到更多详解 Python 语法的文章。源代码可以在https://github.com/brettcannon/desugar上找到。更正2020-08-19修复了当__rsub__() 比 __sub__() 先调用时的规则。2020-08-22修复了当类型相同时不调用__rsub__ 的问题还精简了过渡代码仅保留开头和结尾代码这让我轻松些。2020-08-23在多数示例中添加了内容。