For a specific operator, two types are considered incompatible if no built-in operations between those types exist and none of the operands has
implemented the operator’s corresponding special methods. Performing such an operation on incompatible types will raise a TypeError
.
Calling an operator in Python is equivalent to calling a special method (except for the identity operator is
). Python provides a set
of built-in operations. For example, to add two integers: 1 + 2
, calling the built-in operator +
is equivalent to calling
the special method __add__
on the type int
.
Python allows developers to define how an operator will behave with a custom class by implementing the corresponding special method. When defining
such methods for symmetrical binary operators, developers need to define two methods so that the order of operands doesn’t matter, ex:
__add__
and __radd__
.
For a complete list of operators and their methods see the Python documentation: arithmetic and bitwise operators, comparison operators.