Python - Right-Side and In-Place Add: __iadd__


The __add__ methods coded do not support the use of instance objects on the right side of the + operator:


class Adder: 
   def __init__(self, value=0): = value # from w w  w  . ja  v  a  2 s . c o  m
   def __add__(self, other): 
       return + other 

x = Adder(5) 
print( x + 2 )
print( 2 + x )


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 Adder1: 
    def __init__(self, val): 
        self.val = val # from   w w w  . j av a  2 s.c  o m
    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 = Adder1(88) 
y = Adder1(99) 
print( x + 1 )                     # __add__: instance + noninstance 
print( 1 + y )                     # __radd__: noninstance + instance 
print( x + y )                     # __add__: instance + instance, triggers __radd__


Related Topics