Sub topic 18
Operator Overloading with Special Methods
This chapter assumes you can write a Python class with __init__ and methods, and that you know how +, ==, and isinstance behave on built-in types.
How operators map to methods
When Python evaluates a + b, it calls a.__add__(b). Operators are syntax for special methods, also called dunder methods because their names have double underscores. A class that defines these methods works with the same operators as built-in types.
| Expression | Method called |
|---|---|
| `a + b` | `a.__add__(b)` |
| `a - b` | `a.__sub__(b)` |
| `a * b` | `a.__mul__(b)` |
| `a == b` | `a.__eq__(b)` |
| `a < b` | `a.__lt__(b)` |
A worked example
The Vector class below supports + and ==. It also defines __repr__ so that printed results are readable.
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.x == other.x and self.y == other.y
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4))
print(Vector(1, 2) == Vector(1, 2))The output is Vector(4, 6) and then True.
Returning NotImplemented
If other is not a Vector, the methods return NotImplemented. This is a special value, not an exception. It tells Python that this operand does not know how to handle the operation.
Python then tries the other operand's reflected method, such as __radd__. If that also fails, Python raises TypeError for arithmetic. For ==, it falls back to an identity comparison, which gives False for two different objects.
Common errors
- Raising instead of returning. Raising
TypeErrorinside__add__stops Python from trying the other operand. ReturnNotImplementedinstead. - Mutating
self.__add__should build and return a new object. Changingselfsurprises callers, becausea + bwould altera. - Defining
__eq__alone. A class that defines__eq__without__hash__becomes unhashable, so its instances cannot be dict keys or set members. Add__hash__if you need that, and make it consistent with__eq__. - Missing reflected methods.
Vector(1, 2) + 5fails, and so would5 + Vector(1, 2), becauseintreturnsNotImplementedand the vector has no__radd__. Define__radd__only if the operation makes sense in that order.
Exercise
Exercise
What does Python do for Vector(1, 2) + 5 with the class above, and why?
Show answer
It raises TypeError. Vector._add sees that 5 is not a Vector and returns NotImplemented. Python then tries int.radd_(5, vector), which also returns NotImplemented. With both sides declining, Python raises TypeError.
Exercise
Add a _sub_ method to Vector so that Vector(5, 5) - Vector(1, 2) gives Vector(4, 3). What should it return for a non-Vector operand?
Show answer
def _sub_(self, other): if not isinstance(other, Vector): return NotImplemented return Vector(self.x - other.x, self.y - other.y) For a non-Vector operand it returns NotImplemented, so Python can try the other side or raise TypeError.