Python Language Overloading Operator overloading


Example

Below are the operators that can be overloaded in classes, along with the method definitions that are required, and an example of the operator in use within an expression.

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

OperatorMethodExpression
+ Addition__add__(self, other)a1 + a2
- Subtraction__sub__(self, other)a1 - a2
* Multiplication__mul__(self, other)a1 * a2
@ Matrix Multiplication__matmul__(self, other)a1 @ a2 (Python 3.5)
/ Division__div__(self, other)a1 / a2 (Python 2 only)
/ Division__truediv__(self, other)a1 / a2 (Python 3)
// Floor Division__floordiv__(self, other)a1 // a2
% Modulo/Remainder__mod__(self, other)a1 % a2
** Power__pow__(self, other[, modulo])a1 ** a2
<< Bitwise Left Shift__lshift__(self, other)a1 << a2
>> Bitwise Right Shift__rshift__(self, other)a1 >> a2
& Bitwise AND__and__(self, other)a1 & a2
^ Bitwise XOR__xor__(self, other)a1 ^ a2
| (Bitwise OR)__or__(self, other)a1 | a2
- Negation (Arithmetic)__neg__(self)-a1
+ Positive__pos__(self)+a1
~ Bitwise NOT__invert__(self)~a1
< Less than__lt__(self, other)a1 < a2
<= Less than or Equal to__le__(self, other)a1 <= a2
== Equal to__eq__(self, other)a1 == a2
!= Not Equal to__ne__(self, other)a1 != a2
> Greater than__gt__(self, other)a1 > a2
>= Greater than or Equal to__ge__(self, other)a1 >= a2
[index] Index operator__getitem__(self, index)a1[index]
in In operator__contains__(self, other)a2 in a1
(*args, ...) Calling__call__(self, *args, **kwargs)a1(*args, **kwargs)

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 start 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.

FunctionMethodExpression
Casting to int__int__(self)int(a1)
Absolute function__abs__(self)abs(a1)
Casting to str__str__(self)str(a1)
Casting to unicode__unicode__(self)unicode(a1) (Python 2 only)
String representation__repr__(self)repr(a1)
Casting to bool__nonzero__(self)bool(a1)
String formatting__format__(self, formatstr)"Hi {:abc}".format(a1)
Hashing__hash__(self)hash(a1)
Length__len__(self)len(a1)
Reversed__reversed__(self)reversed(a1)
Floor__floor__(self)math.floor(a1)
Ceiling__ceil__(self)math.ceil(a1)

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