Python Reference ยท Classes and Special Methods
__add__() and arithmetic methods
Reference for Python __add__(), __radd__(), __iadd__() and the other arithmetic special methods: operator overloading, NotImplemented and reflected operands.
Python turns an operator into a method call. When you write a + b, Python calls a.__add__(b). If that method does not exist, or returns the special value NotImplemented, Python tries the reflected method b.__radd__(a). Defining these methods lets your own classes work with +, -, * and the rest.
Every binary operator has three variants: the normal method (__add__), the reflected method with an r prefix (__radd__), and the in-place method with an i prefix (__iadd__, used by +=).
class Money: def __init__(self, cents): self.cents = cents def __add__(self, other): if not isinstance(other, Money): return NotImplemented return Money(self.cents + other.cents)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
def __add__(self, other): ... # self + other def __radd__(self, other): ... # other + self, when other.__add__ fails def __iadd__(self, other): ... # self += other def __neg__(self): ... # -self
The table lists the common operators. Each has the same three forms.
| Operator | Method | Reflected | In-place |
|---|---|---|---|
+ |
__add__ |
__radd__ |
__iadd__ |
- |
__sub__ |
__rsub__ |
__isub__ |
* |
__mul__ |
__rmul__ |
__imul__ |
/ |
__truediv__ |
__rtruediv__ |
__itruediv__ |
// |
__floordiv__ |
__rfloordiv__ |
__ifloordiv__ |
% |
__mod__ |
__rmod__ |
__imod__ |
** |
__pow__ |
__rpow__ |
__ipow__ |
@ |
__matmul__ |
__rmatmul__ |
__imatmul__ |
&, |, ^ |
__and__, __or__, __xor__ |
__rand__, __ror__, __rxor__ |
__iand__, __ior__, __ixor__ |
<<, >> |
__lshift__, __rshift__ |
__rlshift__, __rrshift__ |
__ilshift__, __irshift__ |
Unary operators use __neg__ (-x), __pos__ (+x), __abs__ (abs(x)) and __invert__ (~x).
| Parameter | Description |
|---|---|
self |
The left operand (for the reflected form, the right operand). |
other |
The operand on the other side of the operator. |
Return value: the result of the operation, or NotImplemented when your class does not know how to handle other.
Raises: nothing by default. If both sides return NotImplemented, Python raises TypeError: unsupported operand type(s).
Usage notes
- Return
NotImplemented, do not raiseTypeError. The value (not the exception) tells Python to try the other operand. RaisingTypeErroryourself blocks the reflected method. - Reflected methods run second, with one exception: if the right operand's class is a subclass of the left operand's class and overrides the reflected method, it goes first.
sum()starts with0, sosum()over your objects calls0 + obj, which needs__radd__. Pass a start value (sum(items, Money(0))) to avoid it.- In-place methods may mutate.
x += ycalls__iadd__and rebindsxto whatever it returns. If__iadd__is missing, Python falls back tox = x + y. Immutable types should not define in-place methods. - Comparison operators are separate: see
__lt__()and__eq__(). - Keep operators intuitive. Overload an operator only when its meaning is obvious, such as vectors, money or sets, and return a new object so the operands stay unchanged.
- Augmented methods for
divmod()use__divmod__and__rdivmod__; the three-argumentpow(a, b, mod)calls__pow__with an extra argument. functools.total_orderingandnumbers.Numberhelp when you implement many operators.