all Python 3OOPfunction
__add__
magic methods
The method behind +: a + b calls a.__add__(b). Returning NotImplemented hands the turn to b.__radd__(a).
Syntax
def __add__(self, other): ...
When __add__ cannot handle the other operand's type it should return NotImplemented rather than raise TypeError: Python then tries the reflected __radd__ of the right operand and only after that reports an error. a += b looks for __iadd__ first and falls back to __add__ only without it — which is exactly how immutable types are meant to work.
Examples
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.amount + other.amount)
print((Money(5) + Money(7)).amount) # → 12
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return NotImplemented
Money(1) + 2 # → TypeError: unsupported operand type(s) for +
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy