Python - In-Place Addition: __iadd__

Introduction

To implement += in-place augmented addition, code either an __iadd__ or an __add__.

The latter is used if the former is absent.

Demo

class Number: 
    def __init__(self, val): 
        self.val = val #   w w w .  j av  a2s .  c  om
    def __iadd__(self, other):             # __iadd__ explicit: x += y 
        self.val += other                  # Usually returns self 
        return self 

x = Number(5) 
x += 1 
x += 1 
x.val 

#For mutable objects, 
#this method can often specialize for quicker in-place changes: 

y = Number([1])                            # In-place change faster than + 
y += [2] 
y += [3] 
y.val

The normal __add__ method is run as a fallback, but may not be able optimize in-place cases:

Demo

class Number: 
    def __init__(self, val): 
        self.val = val # from  ww  w. j a va 2  s  .  c  o  m
    def __add__(self, other):              # __add__ fallback: x = (x + y) 
        return Number(self.val + other)    # Propagates class type 

x = Number(5) 
x += 1 
x += 1                                     # And += does concatenation here 
x.val

Related Topic