Sub topic 18
Operator overloading with special methods
This chapter assumes you can write a Python class with __init__, and that you know the operators from the earlier chapters: arithmetic, comparison, in, and the truthiness rules. Here you will see that those operators are calls to special methods, and you will make your own classes work with them.
Operators are method calls
When Python evaluates a + b, it calls type(a).__add__(a, b). Comparison, unary minus, len(), and bool() work the same way. A method whose name starts and ends with two underscores is a special method (also called a dunder method). Python looks special methods up on the type, not on the instance, so assigning obj.__add__ = ... has no effect on +.
| Expression | Method called |
|---|---|
| `a + b`, `a - b`, `a * b` | `__add__`, `__sub__`, `__mul__` |
| `a / b`, `a // b`, `a % b` | `__truediv__`, `__floordiv__`, `__mod__` |
| `a == b`, `a != b` | `__eq__`, `__ne__` |
| `a < b`, `a <= b`, `a > b`, `a >= b` | `__lt__`, `__le__`, `__gt__`, `__ge__` |
| `-a`, `abs(a)` | `__neg__`, `__abs__` |
| `x in a` | `__contains__` |
| `bool(a)`, `if a:` | `__bool__`, then `__len__` |
| `a += b` | `__iadd__`, falling back to `__add__` |
A first operator-aware class
The class below supports +, ==, scalar multiplication, negation, and truthiness.
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 __mul__(self, scalar):
if not isinstance(scalar, (int, float)):
return NotImplemented
return Vector(self.x * scalar, self.y * scalar)
__rmul__ = __mul__
def __neg__(self):
return Vector(-self.x, -self.y)
def __eq__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return self.x == other.x and self.y == other.y
def __hash__(self):
return hash((self.x, self.y))
def __bool__(self):
return self.x != 0 or self.y != 0
def __repr__(self):
return f"Vector({self.x}, {self.y})"
print(Vector(1, 2) + Vector(3, 4))
print(3 * Vector(1, 2))
print(-Vector(1, 2))
print(Vector(1, 2) == Vector(1, 2))
print(bool(Vector(0, 0)))
try:
Vector(1, 2) + 5
except TypeError as error:
print(error)The output is:
Vector(4, 6)
Vector(3, 6)
Vector(-1, -2)
True
False
unsupported operand type(s) for +: 'Vector' and 'int'Each method returns a new Vector instead of changing self. Arithmetic operators are expected to behave like they do on numbers and strings, which produce new values.
Returning NotImplemented
When a method cannot handle the other operand, it should return NotImplemented. This is a special value, not an exception, and it is not the same as NotImplementedError. It tells Python to try the next option. Raising a TypeError yourself would stop that fallback.
For a + b Python follows these steps:
One exception: if type(b) is a subclass of type(a) and overrides the reflected method, Python tries the right operand first. This lets a subclass take control of mixed operations.
That is why 3 * Vector(1, 2) works above. int.__mul__ returns NotImplemented for a Vector, so Python calls Vector.__rmul__. For * the order of operands does not matter, so aliasing __rmul__ = __mul__ is enough. For - or / the reflected method must swap the order itself, because __rsub__(self, other) computes other - self.
Equality, hashing, and ordering
Equality has three rules to remember.
- If you do not define
__eq__, objects compare by identity, as withis. __ne__is derived from__eq__automatically, so you rarely write it.- If you define
__eq__without__hash__, Python sets__hash__toNone. The instances then cannot be dictionary keys or set members. Define both, built from the same fields, and keep the object unchanged while it is used as a key.
For ordering, you can define all four of __lt__, __le__, __gt__, __ge__. It is shorter to define __eq__ and one of them, then let functools.total_ordering generate the rest.
from functools import total_ordering
@total_ordering
class Version:
def __init__(self, text):
self.parts = tuple(int(p) for p in text.split("."))
def __eq__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts == other.parts
def __lt__(self, other):
if not isinstance(other, Version):
return NotImplemented
return self.parts < other.parts
def __hash__(self):
return hash(self.parts)
def __repr__(self):
return f"Version({'.'.join(map(str, self.parts))!r})"
print(Version("1.2") < Version("1.10"))
print(Version("1.2") >= Version("1.2"))
print(max(Version("1.2"), Version("1.10"), Version("1.9")))
print(Version("1.0") < Version("1.5") < Version("2.0"))This prints True, True, Version('1.10'), and True. The last line shows that a chained comparison works on your class with no extra code, because it is just two < calls. Comparing the tuples of integers makes 1.10 larger than 1.2. Comparing the strings would not.
Truthiness and containers
bool(obj) calls __bool__ if it exists. Otherwise Python calls __len__ and treats 0 as false. If neither exists, the object is always true. This is how if vector: and value or default behave on your classes.
x in obj calls __contains__. If that is missing, Python falls back to iterating over the object, and then to __getitem__ with integer indexes.
In-place operators
a += b first tries __iadd__. If it is missing or returns NotImplemented, Python evaluates a = a + b. A mutable class can implement __iadd__ to change itself and must return self.
class Bag:
def __init__(self):
self.items = []
def __iadd__(self, item):
self.items.append(item)
return self
bag = Bag()
alias = bag
bag += "apple"
print(alias.items)
print(alias is bag)Both lines show the in-place behavior: ['apple'] and True. This is the same effect you see with lists, where += changes the original object that other names point to.
What you cannot overload
and,or,not,is,is not, and the walrus:=have no special methods.andandormust short-circuit, andismust compare identity, so Python keeps them fixed.not xuses__bool__through truthiness, but you cannot changenotitself.- Operator precedence is fixed. A class cannot change how
a + b * cis grouped. - The built-in types cannot be changed. You cannot make
int + strwork. You can only make your own class cooperate.
Common mistakes
- Raising
TypeErrorinstead of returningNotImplemented, which blocks the reflected method. - Defining
__eq__and forgetting__hash__, then gettingunhashable typewhen using the object in a set. - Making
==accept every type. ReturningFalsefor unrelated types is fine, but returningNotImplementedlets the other operand answer first. - Returning something surprising from an operator, such as
+that modifiesself. - Overusing overloading. Use it when the operator reads naturally for your type, such as vectors, money, or versions. Use a named method when it does not.
Exercise
A class Money defines __add__ that raises TypeError when other is not a Money. Why does sum([Money(1), Money(2)]) fail, and what two changes make it work?
Show answer
sum starts with the integer 0, so the first step is 0 + Money(1). int.__add__ returns NotImplemented, and then Python calls Money.__radd__, which is not defined, so a TypeError results. The fix is to define __radd__ so that it accepts 0 and returns self for it (or to call sum(..., Money(0))), and to have __add__ return NotImplemented instead of raising so that Python's fallback can run.
Exercise
What does this print, and why? class P: with def __init__(self, n): self.n = n, and def __eq__(self, other): return self.n == other.n. Then s = {P(1)}.
Show answer
The line s = {P(1)} raises TypeError: unhashable type: 'P'. Defining __eq__ without __hash__ sets __hash__ to None, so P instances cannot be put in a set. Adding def __hash__(self): return hash(self.n) fixes it.