在习题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