__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__追加も実装する機会が与えられます。
2 つのタイプ と を追加しようとする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