您还需要添加__radd__
以处理相反的情况:
def __radd__(self, other):
if isinstance(other, C):
return other.value + self.value
if isinstance(other, Number):
return other + self.value
return NotImplemented
并注意您不应引发异常;NotImplemented
而是返回单例。这样,其他对象仍然可以尝试支持__add__
或__radd__
支持您的对象,并且也将有机会实现加法。
当您尝试添加两种类型a
时b
,Python首先尝试调用a.__add__(b)
;如果该调用返回NotImplemented
,b.__radd__(a)
则改为尝试。
演示:
>>> from numbers import Number
>>> class C(object):
... def __init__(self, value):
... self.value = value
... def __add__(self, other):
... print '__add__ called'
... if isinstance(other, C):
... return self.value + other.value
... if isinstance(other, Number):
... return self.value + other
... return NotImplemented
... def __radd__(self, other):
... print '__radd__ called'
... if isinstance(other, C):
... return other.value + self.value
... if isinstance(other, Number):
... return other + self.value
... return NotImplemented
...
>>> c = C(123)
>>> c + c
__add__ called
246
>>> c + 2
__add__ called
125
>>> 2 .__add__(c)
NotImplemented
>>> 2 + c
__radd__ called
125