Overload __radd__ method to handle right side addition
Overload __radd__
__radd__
handles right-side addition.
class Commuter: # w ww .j a v a2 s .c o m
def __init__(self, val):
self.val = val
def __add__(self, other):
print 'add', self.val, other
def __radd__(self, other):
print 'radd', self.val, other
x = Commuter(88)
y = Commuter(99)
x + 1 # __add__: instance + noninstance
1 + y # __radd__: noninstance + instance
x + y # __add__: instance + instance
The code above generates the following result.