python核心程式設計學習筆記-2016-08-15-01-左加法__add__和右加法__radd__
阿新 • • 發佈:2019-01-01
在習題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不能是同一個類的例項。比如下面的例子:
參考自http://stackoverflow.com/questions/4298264/why-is-radd-not-working>>> 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'