python核心编程学习笔记-2016-08-15-01-左加法

    xiaoxiao2026-01-09  7

             在习题13-20中,出现了__radd__()函数。

             __radd__(self, other)和__add__(self, other)都是定制类的加法,前者表示右加法other + self,后者表示左加法self + other。

            python在执行加法a + b的过程中,首先是查找a是否有左加法方法__add__(self, other),如果有就直接调用,如果没有,就查找b是否有右加法__radd__(self, other),如果有就调用此方法,如果没有就引发类型异常。

            但是要注意,__radd__(self, other)的调用是有前提的,就是self和other不能是同一个类的实例。比如下面的例子:

    >>> class X(object): def __init__(self, x): self.x = x def __radd__(self, other): return X(self.x + other.x) >>> a = X(5) >>> b = X(10) >>> a + b Traceback (most recent call last): File "<pyshell#8>", line 1, in <module> a + b TypeError: unsupported operand type(s) for +: 'X' and 'X' >>> b + a Traceback (most recent call last): File "<pyshell#9>", line 1, in <module> b + a TypeError: unsupported operand type(s) for +: 'X' and 'X' 参考自 http://stackoverflow.com/questions/4298264/why-is-radd-not-working

    转载请注明原文地址: https://ju.6miu.com/read-1305819.html
    最新回复(0)