Sub topic 7
Overloading arithmetic operators
This chapter assumes you can define classes with instance attributes and methods, and that you know isinstance and basic tuple and list behavior. It covers the binary arithmetic hooks. Reflected operators, in-place operators and unary operators get their own chapters.
How an operator becomes a method call
When Python evaluates a + b, it looks up __add__ on the type of a and calls a.__add__(b). The same pattern holds for the other arithmetic operators.
| Operator | Method |
|---|---|
| `+` | `__add__` |
| `-` | `__sub__` |
| `*` | `__mul__` |
| `/` | `__truediv__` |
| `//` | `__floordiv__` |
| `%` | `__mod__` |
| `**` | `__pow__` |
| `@` | `__matmul__` |
Python looks these methods up on the type, not on the instance. Assigning v.__add__ = something to one object does not change how v + w behaves.
A Vector with + and scalar *
class Vector:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f'Vector({self.x!r}, {self.y!r})'
def __add__(self, other):
if not isinstance(other, Vector):
return NotImplemented
return Vector(self.x + other.x, self.y + other.y)
def __sub__(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)
print(Vector(1, 2) + Vector(3, 4)) # Vector(4, 6)
print(Vector(5, 5) - Vector(1, 2)) # Vector(4, 3)
print(Vector(1, 2) * 3) # Vector(3, 6)Two design choices matter here.
- Each method returns a new
Vector. It does not modifyself. Callers expecta + bto leaveaandbunchanged. - Each method checks the operand type and returns
NotImplementedwhen it does not support it. This is a special value, not an exception.
Why return NotImplemented
NotImplemented tells Python that this method cannot handle the operand. Python then tries the other operand's reflected method. If that also fails, Python raises TypeError with a clear message.
try:
Vector(1, 2) + 5
except TypeError as e:
print(e) # unsupported operand type(s) for +: 'Vector' and 'int'The first common error is raising TypeError yourself inside __add__. That stops Python from trying the other operand, so another class that knows how to add itself to a Vector never gets the chance. The second common error is writing return NotImplementedError, which is an exception class and not the special value. It silently returns a wrong result.
Order matters
Vector(1, 2) * 3 works, but 3 * Vector(1, 2) raises TypeError. The int type's __mul__ returns NotImplemented for a Vector, and Vector has no reflected method yet. The next chapter fixes this with __rmul__.
Other habits
- Keep operand types strict. Accepting only what you have defined makes errors visible early.
- Do not mutate inputs. Return new objects.
- Keep the meaning familiar.
+should behave like addition, not like appending to a log.
Exercise
Add a __truediv__ method to Vector so that Vector(4, 6) / 2 returns Vector(2.0, 3.0). What should it return when the divisor is a string, and why?
Show answer
Check the divisor with isinstance(scalar, (int, float)). If it fails, return NotImplemented, so Python raises TypeError instead of the method deciding for itself. When it passes, return Vector(self.x / scalar, self.y / scalar). Dividing by zero then raises ZeroDivisionError naturally, which is the correct behavior.