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

Introduction

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

Demo

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

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

Result

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:

Demo

class Adder1: 
    def __init__(self, val): 
        self.val = val # from w  ww.  j  av  a 2s. co 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__

Result

Related Topics