Operator overloading

suggest change

The table of overloadable operators is not on this page. What follows is the reflected and in-place pattern, plus one example of each.

N.B. The use of other as a variable name is not mandatory, but is considered the norm.

The optional parameter modulo for __pow__ is only used by the pow built-in function.

Each of the methods corresponding to a binary operator has a corresponding “right” method which starts with __r, for example __radd__:

class A:
    def __init__(self, a):
        self.a = a
    def __add__(self, other):
        return self.a + other
    def __radd__(self, other):
        print("radd")
        return other + self.a

A(1) + 2  # Out:  3
2 + A(1)  # prints radd. Out: 3

as well as a corresponding inplace version, starting with __i:

class B:
    def __init__(self, b):
        self.b = b
    def __iadd__(self, other):
        self.b += other
        print("iadd")
        return self

b = B(2)
b.b       # Out: 2
b += 1    # prints iadd
b.b       # Out: 3

Since there’s nothing special about these methods, many other parts of the language, parts of the standard library, and even third-party modules add magic methods on their own, like methods to cast an object to a type or checking properties of the object. For example, the builtin str() function calls the object’s __str__ method, if it exists. Some of these uses are listed below.

There are also the special methods __enter__ and __exit__ for context managers, and many more.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents