Skip to content
Tutorials Center
My learning

Topics

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 +=).

Python
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

Python A Vector with + and *

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.

Python Reflected and in-place methods

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

Python
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 raise TypeError. The value (not the exception) tells Python to try the other operand. Raising TypeError yourself 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 with 0, so sum() over your objects calls 0 + obj, which needs __radd__. Pass a start value (sum(items, Money(0))) to avoid it.
  • In-place methods may mutate. x += y calls __iadd__ and rebinds x to whatever it returns. If __iadd__ is missing, Python falls back to x = 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-argument pow(a, b, mod) calls __pow__ with an extra argument.
  • functools.total_ordering and numbers.Number help when you implement many operators.