![]() |
VOOZH | about |
Operator overloading allows the same operator to perform different actions depending on the objects it works with. Python supports operator overloading for both built-in data types and user-defined classes.
The following example shows how the same operators can produce different results depending on the data type.
3 GeeksFor 12 GeeksGeeksGeeksGeeks
Explanation:
By default, Python does not know how operators should behave for objects of a custom class. To define this behavior, Python provides special methods (also called magic methods) that are automatically invoked when operators are used.
Some commonly used operator methods are:
__add__(self, other) -> +
__sub__(self, other) -> -
__eq__(self, other) -> ==
For example, when we write obj1 + obj2. Python internally executes:
obj1.__add__(obj2)
If the __add__() method is defined in the class, the + operator works according to the logic provided in that method.
Example 1: The following example overloads the + operator for objects of a custom class.
3 3 3
Explanation:
Example 2: The following example overloads the + operator to add the real and imaginary parts of two complex numbers.
(3, 5)
Explanation:
Operators like >, <, and == can also be overloaded.
Example 1: This code shows how to overload > operator to compare two objects based on their stored values.
ob2 is greater than ob1
Example 2: This code shows how to overload both < and == operators for custom comparisons.
ob1 is less than ob2 Both are equal
Not all operators can be chained. Some are non-associative. For example, = and += cannot be combined in one statement.
Explanation: In Python, = (assignment) and += (augmented assignment) cannot be mixed in same expression because they are non-associative.
We can also overload Boolean operators using magic methods:
Example: This code shows how to overload & operator so it works like logical AND on custom objects.
False
Explanation: Here, we redefined & so it works like logical AND for custom objects.
Python provides specific methods for each operator.
| Operator | Magic Method |
|---|---|
| + | __add__(self, other) |
| - | __sub__(self, other) |
| * | __mul__(self, other) |
| / | __truediv__(self, other) |
| // | __floordiv__(self, other) |
| % | __mod__(self, other) |
| ** | __pow__(self, other) |
| Operator | Magic Method |
|---|---|
| < | __lt__(self, other) |
| > | __gt__(self, other) |
| <= | __le__(self, other) |
| >= | __ge__(self, other) |
| == | __eq__(self, other) |
| != | __ne__(self, other) |
| Operator | Magic Method |
|---|---|
| -= | __isub__(self, other) |
| += | __iadd__(self, other) |
| *= | __imul__(self, other) |
| /= | __itruediv__(self, other) |
| //= | __ifloordiv__(self, other) |
| %= | __imod__(self, other) |
| **= | __ipow__(self, other) |
| Operator | Magic Method |
|---|---|
| - | __neg__(self) |
| + | __pos__(self) |
| ~ | __invert__(self) |
Overloading operators in custom classes provides several benefits: