Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.
Technically, the __add__ method that
appeared in the prior example does not support the use of instance
objects on the right side of the +
operator. To implement such expressions, and hence support commutative-style
operators, code the __radd__ method
as well. Python calls __radd__ only
when the object on the right side of the + is your class instance, but the object on
the left is not an instance of your class. The __add__ method for the object on the left is
called instead in all other cases:
>>>class Commuter:...def __init__(self, val):...self.val = val...def __add__(self, other):...print('add', self.val, other)...return self.val + other...def __radd__(self, other):...print('radd', self.val, other)...return other + self.val... >>>x = Commuter(88)>>>y = Commuter(99)>>>x + 1# __add__: instance + noninstance add 88 1 89 >>>1 + y# __radd__: noninstance + instance radd 99 1 100 >>>x + y# __add__: instance + instance, triggers __radd__ add 88 <__main__.Commuter object at 0x02630910> radd 99 88 187