Operator Overloading
Published by Brayan K
Master operator overloading to make your classes behave like built-in types. Learn the techniques used by NumPy, PyTorch, Pandas, and SQLAlchemy to create intuitive, powerful APIs through custom operator behaviors.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
a + b asks a's class for __add__
This lesson is about operators: +, *, <, +=, -x and the rest. What len(), print(), in, for, if, calling and == ask an object for is in Magic Methods & the Python Data Model.
Inheritance and Polymorphism showed that + means something different for each type. Each type decides with a special method: a + b asks a's class for __add__. The built-in types use this for more than arithmetic: | combines two sets in Sets, and / joins paths in Modern File Paths with pathlib:
from pathlib import PurePosixPath
print("tea" + "pot", [1] + [2], 1 + 2)
print(sorted({1, 2} | {2, 3}))
print(PurePosixPath("reports") / "q1.csv")
print(hasattr(PurePosixPath, "__truediv__"), hasattr(str, "__truediv__"))
# ✅ Expected output:
# teapot [1, 2] 3
# [1, 2, 3]
# reports/q1.csv
# True False/ asks for __truediv__, which a path's class has and str doesn't. Your own class gets an operator the same way. This Money keeps whole pence in an int, so its sums are exact (why a float isn't safe for money is in Numbers: int, float, Decimal & Fraction):
class Money:
def __init__(self, pence):
self.pence = pence
def __repr__(self):
return f"Money({self.pence})"
def __add__(self, other):
return Money(self.pence + other.pence)
tea = Money(250)
cake = Money(325)
print(tea + cake)
print(tea, cake)
print(Money.__add__(tea, cake))
# ✅ Expected output:
# Money(575)
# Money(250) Money(325)
# Money(575)tea + cake runs Money.__add__(tea, cake). It returns a new Money and leaves both operands as they were, as + does for numbers. Each operator has its own method:
| Operator | Method | Operator | Method |
|---|---|---|---|
| + | __add__ | @ | __matmul__ |
| - | __sub__ | & | __and__ |
| * | __mul__ | | | __or__ |
| / | __truediv__ | ^ | __xor__ |
| // | __floordiv__ | << | __lshift__ |
| % | __mod__ | >> | __rshift__ |
| ** | __pow__ |
When the other value is the wrong type
Money's __add__ takes it for granted that the other value is Money too. Given a number, it fails inside the method, with an error about .pence rather than about adding:
class Money:
def __init__(self, pence):
self.pence = pence
def __repr__(self):
return f"Money({self.pence})"
def __add__(self, other):
return Money(self.pence + other.pence)
print(Money(250) + 100)
# ✅ Expected error:
# AttributeError: 'int' object has no attribute 'pence'Sometimes it doesn't fail at all. A Vec whose __mul__ multiplies each coordinate by whatever it's given turns * "ab" into string repetition, and a second Vec into an error about types you never multiplied:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __mul__(self, n):
return Vec(self.x * n, self.y * n)
print(Vec(3, 4) * 2)
print(Vec(3, 4) * "ab")
print(Vec(3, 4) * Vec(1, 2))
# ✅ Expected output:
# Vec(6, 8)
# Vec(ababab, abababab)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for *: 'int' and 'Vec'The int and the Vec in that last error come from inside the method, where self.x * n was 3 * Vec(1, 2).
The fix is the one Magic Methods & the Python Data Model used for ==: check the type, and return NotImplemented for anything the method doesn't handle. Python then gives the other value its turn, as the next section shows, and if that can't help either, it stops with a TypeError that names the operator and both types:
class Money:
def __init__(self, pence):
self.pence = pence
def __repr__(self):
return f"Money({self.pence})"
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.pence + other.pence)
print(Money(250) + Money(325))
print(Money(250) + 100)
# ✅ Expected output:
# Money(575)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'Money' and 'int'Where == fell back on asking whether the two are the same object, and said False, an arithmetic operator has nothing to fall back on, so the TypeError is the answer. Note that NotImplemented is returned, not raised. It isn't an exception, so raise NotImplemented stops with TypeError: exceptions must derive from BaseException. NotImplementedError, which Inheritance and Polymorphism's Shape raised for a method each subclass must write, is an exception, and raising it from __add__ stops the program without asking the other value.
2 * v: Python asks the int, then your __rmul__
v * 2 asks Vec. 2 * v asks int first, and int doesn't know how to multiply by a Vec:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __mul__(self, n):
if not isinstance(n, (int, float)):
return NotImplemented
return Vec(self.x * n, self.y * n)
print(Vec(3, 4) * 2)
print(2 * Vec(3, 4))
# ✅ Expected output:
# Vec(6, 8)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for *: 'int' and 'Vec'When the left value's method returns NotImplemented, or it has none, Python asks the right value for the reflected method: __radd__, __rmul__ and so on, each name with an r in front. This class prints each time it's asked:
class Loud:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
def __add__(self, other):
print(f"{self.name}.__add__({other!r})")
return NotImplemented
def __radd__(self, other):
print(f"{self.name}.__radd__({other!r})")
return NotImplemented
a = Loud("a")
for left, right in [(a, 1), (1, a), (a, Loud("b"))]:
try:
left + right
except TypeError as e:
print("TypeError:", e)
# ✅ Expected output:
# a.__add__(1)
# TypeError: unsupported operand type(s) for +: 'Loud' and 'int'
# a.__radd__(1)
# TypeError: unsupported operand type(s) for +: 'int' and 'Loud'
# a.__add__(b)
# TypeError: unsupported operand type(s) for +: 'Loud' and 'Loud'For a + 1, Python asks a.__add__, then int's __radd__, which prints nothing and can't add a Loud either. For 1 + a, int's __add__ says no without printing, and then a.__radd__ is asked. Between two Louds, no __radd__ is asked at all: Python asks a reflected method only when the two values' types differ.
So a Vec that should multiply from either side needs __rmul__. Multiplying by a number gives the same answer either way round, so the class can give the same function a second name:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __mul__(self, n):
if not isinstance(n, (int, float)):
return NotImplemented
return Vec(self.x * n, self.y * n)
__rmul__ = __mul__
v = Vec(3, 4)
print(v * 2, 2 * v, 0.5 * v)
print(v * v)
# ✅ Expected output:
# Vec(6, 8) Vec(6, 8) Vec(1.5, 2.0)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for *: 'Vec' and 'Vec'That shortcut only suits an operator whose order doesn't matter. 5 - v asks v.__rsub__(5), which has to work out 5 - v, not v - 5.
sum() runs into the same question. It starts from 0, so its first step is 0 + Money(250), which int can't do:
class Money:
def __init__(self, pence):
self.pence = pence
def __repr__(self):
return f"Money({self.pence})"
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.pence + other.pence)
prices = [Money(250), Money(325)]
print(sum(prices, Money(0)))
print(sum(prices))
# ✅ Expected output:
# Money(575)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'int' and 'Money'Giving sum() a start of the right type, its second argument, is one fix. The other is an __radd__ that accepts that 0, so sum() works without a start:
class Money:
def __init__(self, pence):
self.pence = pence
def __repr__(self):
return f"Money({self.pence})"
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.pence + other.pence)
def __radd__(self, other):
if other == 0:
return self
return NotImplemented
print(sum([Money(250), Money(325)]))
print(0 + Money(5))
print(1 + Money(5))
# ✅ Expected output:
# Money(575)
# Money(5)
# ✅ Expected error:
# TypeError: unsupported operand type(s) for +: 'int' and 'Money'pathlib uses a reflected method too. "reports" / PurePosixPath("q1.csv") works because str has no __truediv__ and a path has __rtruediv__:
from pathlib import PurePosixPath
print("reports" / PurePosixPath("q1.csv"))
print(hasattr(str, "__truediv__"), hasattr(PurePosixPath, "__rtruediv__"))
# ✅ Expected output:
# reports/q1.csv
# False TrueCalling the method yourself skips the asking
The operator does the asking, not the method. Call __mul__ yourself and you get whatever it returns, NotImplemented included. That's the bug in this Money:
class Money:
def __init__(self, amount):
self.amount = amount
def __repr__(self):
return f"Money({self.amount})"
def __mul__(self, n):
return Money(self.amount.__mul__(n))
print(Money(100) * 3)
print(Money(100) * 2.5)
print((100).__mul__(2.5), 100 * 2.5)
# ✅ Expected output:
# Money(300)
# Money(NotImplemented)
# NotImplemented 250.0(100).__mul__(2.5) is int's own method, which can't multiply by a float and says so with NotImplemented. 100 * 2.5 goes on to ask the float, which can. So write self.amount * n, and let the operator do the asking.
+= makes a new object, unless the class changes itself
Operators and Expressions said total += 5 is short for total = total + 5. For a class with only __add__, that's what happens: += makes a new object and points the name at it, and another name for the old object still sees the old values:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x + other.x, self.y + other.y)
start = Vec(1, 1)
pos = start
pos += Vec(2, 3)
print(pos, start, pos is start)
# ✅ Expected output:
# Vec(3, 4) Vec(1, 1) FalseA class can change itself instead, with __iadd__. Python calls it for += and points the name at whatever it returns, so it ends with return self:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
if not isinstance(other, Vec):
return NotImplemented
self.x += other.x
self.y += other.y
return self
start = Vec(1, 1)
pos = start
pos += Vec(2, 3)
print(pos, start, pos is start)
# ✅ Expected output:
# Vec(3, 4) Vec(3, 4) TrueNow every name for that Vec sees the change, like the two names for one list in Lists and Collections. Leave out the return, and the name ends up pointing at None:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x + other.x, self.y + other.y)
def __iadd__(self, other):
self.x += other.x
self.y += other.y
pos = Vec(1, 1)
pos += Vec(2, 3)
print(pos)
print(pos.x)
# ✅ Expected output:
# None
# ✅ Expected error:
# AttributeError: 'NoneType' object has no attribute 'x'Built-in types choose too. A list changes itself; a tuple can't, so it makes a new one:
cart = ["tea"]
saved = cart
cart += ["jam"]
print(cart, saved)
cart = cart + ["bread"]
print(cart, saved)
order = ("tea",)
kept = order
order += ("jam",)
print(order, kept)
# ✅ Expected output:
# ['tea', 'jam'] ['tea', 'jam']
# ['tea', 'jam', 'bread'] ['tea', 'jam']
# ('tea', 'jam') ('tea',)When neither method accepts the other value, the error names +=. With the first Vec in this section, whose __add__ checks the type, pos += 5 stops with TypeError: unsupported operand type(s) for +=: 'Vec' and 'int'.
Ordering: < gives you >, but not <=
< asks for __lt__. With only that, > works too, and so do sorted(), min() and max(), but <= doesn't:
class Score:
def __init__(self, points):
self.points = points
def __repr__(self):
return f"Score({self.points})"
def __lt__(self, other):
return self.points < other.points
a, b = Score(70), Score(90)
print(a < b, a > b)
print(sorted([b, a]), min(b, a), max(a, b))
print(a <= b)
# ✅ Expected output:
# True False
# [Score(70), Score(90)] Score(70) Score(90)
# ✅ Expected error:
# TypeError: '<=' not supported between instances of 'Score' and 'Score'> works because it's the reflection of <: Score has no __gt__, so Python answers a > b with b.__lt__(a). That's also how max(), which asks whether each item is bigger than the biggest so far, gets its answers:
class Score:
def __init__(self, points):
self.points = points
def __repr__(self):
return f"Score({self.points})"
def __lt__(self, other):
print(f"is {self.points} < {other.points}?")
return self.points < other.points
a, b = Score(70), Score(90)
print(max(a, b))
print(a > b)
# ✅ Expected output:
# is 70 < 90?
# Score(90)
# is 90 < 70?
# FalseThere's no such pairing for <=: Python doesn't build it out of < and ==. functools.total_ordering, a decorator for a class, writes the missing comparisons from __eq__ and one ordering method:
from functools import total_ordering
@total_ordering
class Score:
def __init__(self, points):
self.points = points
def __repr__(self):
return f"Score({self.points})"
def __eq__(self, other):
if not isinstance(other, Score):
return NotImplemented
return self.points == other.points
def __lt__(self, other):
if not isinstance(other, Score):
return NotImplemented
return self.points < other.points
a, b = Score(70), Score(90)
print(a <= b, a >= b, a > b, a != b)
print(sorted([b, a, Score(80)]))
print(a == 70)
print(a <= 70)
# ✅ Expected output:
# True False False True
# [Score(70), Score(80), Score(90)]
# False
# ✅ Expected error:
# TypeError: '<=' not supported between instances of 'Score' and 'int'Both methods return NotImplemented for anything that isn't a Score, so a == 70 is simply False and a <= 70 is a TypeError. With no ordering method at all, @total_ordering stops as soon as the class is made, with ValueError: must define at least one ordering operation: < > <= >=.
To order by more than one thing, compare tuples, as Tuples did: the first items decide, and the next ones break a tie.
class Runner:
def __init__(self, name, seconds):
self.name = name
self.seconds = seconds
def __repr__(self):
return f"{self.name} {self.seconds}"
def __lt__(self, other):
return (self.seconds, self.name) < (other.seconds, other.name)
print(sorted([Runner("Bo", 61), Runner("Al", 58), Runner("Ann", 61)]))
# ✅ Expected output:
# [Al 58, Ann 61, Bo 61]A class that mainly holds data can get all of this from @dataclass(order=True), in Data Classes & Advanced Class Patterns. And when objects have no one natural order, leave < out and give sorted() a key=, as Sorting with sorted() & key shows.
Operators with one value, and conversions to numbers
-v asks for __neg__, +v for __pos__, and abs(v), a number's distance from zero, for __abs__. Each one is separate, so a class with __neg__ doesn't get +:
class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __neg__(self):
return Vec(-self.x, -self.y)
def __abs__(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
v = Vec(3, -4)
print(-v, abs(v))
print(+v)
# ✅ Expected output:
# Vec(-3, 4) 5.0
# ✅ Expected error:
# TypeError: bad operand type for unary +: 'Vec'__index__ says an object can stand in for a whole number wherever Python needs an exact int: as a list index, in a slice and in range():
class Floor:
def __init__(self, number):
self.number = number
def __index__(self):
return self.number
lift = Floor(2)
names = ["ground", "first", "second", "third"]
print(names[lift], names[:lift])
print(list(range(lift)), int(lift))
# ✅ Expected output:
# second ['ground', 'first']
# [0, 1] 2__int__ and __float__ are what int() and float() ask for. They're allowed to lose something, such as the pence below a pound, so Python won't use them for an index:
class Money:
def __init__(self, pence):
self.pence = pence
def __int__(self):
return self.pence // 100
def __float__(self):
return self.pence / 100
m = Money(275)
print(int(m), float(m))
print(["a", "b", "c"][m])
# ✅ Expected output:
# 2 2.75
# ✅ Expected error:
# TypeError: list indices must be integers or slices, not Money~x asks for __invert__. On an int it gives -x - 1, so ~4 is -5, which surprises anyone who expected it to switch a setting off. Settings that combine with |, & and ~ are what Enums (the enum module) calls flags.
An operator should mean what it looks like
Python lets == return anything at all, and if then asks that value whether it's true. This Column's == returns a piece of text, so every comparison counts as true:
class Column:
def __init__(self, name):
self.name = name
def __eq__(self, value):
return f"{self.name} = {value!r}"
name = Column("name")
print(name == "Ada")
if name == "Bo":
print("this runs, though nothing was compared")
# ✅ Expected output:
# name = 'Ada'
# this runs, though nothing was comparedDatabase libraries do this on purpose. In SQLAlchemy, which Using SQLite & ORMs (SQLAlchemy) in Python introduces, comparing a column with == builds part of a query instead of giving True or False. In your own classes, give each operator the meaning it has for numbers and the built-in types, so that code using them does what it reads as.
Practice: lap times you can add and compare
Three lap times need adding up and comparing. Fill in the method that + asks for, what __lt__ gives back for anything that isn't a Duration, and the start that sum() needs. Each answer is in the comment on its line; cover the comments if you'd like to work it out first.
from functools import total_ordering
@total_ordering
class Duration:
def __init__(self, seconds):
self.seconds = seconds
def __repr__(self):
return f"Duration({self.seconds})"
def ___(self, other): # 👉 replace ___ with __add__
if not isinstance(other, Duration):
return NotImplemented
return Duration(self.seconds + other.seconds)
def __eq__(self, other):
if not isinstance(other, Duration):
return NotImplemented
return self.seconds == other.seconds
def __lt__(self, other):
if not isinstance(other, Duration):
return ___ # 👉 replace ___ with NotImplemented
return self.seconds < other.seconds
laps = [Duration(95), Duration(88), Duration(91)]
total = sum(laps, ___) # 👉 replace ___ with Duration(0)
print(total)
print(min(laps), max(laps))
print(Duration(88) <= Duration(91), Duration(88) == 88)
# ✅ Expected output:
# Duration(274)
# Duration(88) Duration(95)
# True FalseIf the first blank gets add instead of __add__, sum() stops with TypeError: unsupported operand type(s) for +: 'Duration' and 'Duration', since no method has the name + asks for. Leave out the start, and it's TypeError: unsupported operand type(s) for +: 'int' and 'Duration'.
On your own: a 2-D vector
Write a class Vec for a 2-D vector. It prints as Vec(3, 4); + and - work between two vectors and with nothing else; * multiplies by a number from either side; -v flips both signs; abs(v) is the vector's length; == compares the coordinates; and a vector can go in a set. The lines under the comment test all of it.
# your code here
a = Vec(3, 4)
b = Vec(1, 2)
print(a + b, a - b, 2 * a, a * 0.5)
print(-b, abs(a))
print(a == Vec(3, 4), a == (3, 4), len({a, Vec(3, 4), b}))
try:
a + 1
except TypeError as e:
print("TypeError:", e)class Vec:
def __init__(self, x, y):
self.x = x
self.y = y
def __repr__(self):
return f"Vec({self.x}, {self.y})"
def __add__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x + other.x, self.y + other.y)
def __sub__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return Vec(self.x - other.x, self.y - other.y)
def __mul__(self, n):
if not isinstance(n, (int, float)):
return NotImplemented
return Vec(self.x * n, self.y * n)
__rmul__ = __mul__
def __neg__(self):
return Vec(-self.x, -self.y)
def __abs__(self):
return (self.x ** 2 + self.y ** 2) ** 0.5
def __eq__(self, other):
if not isinstance(other, Vec):
return NotImplemented
return (self.x, self.y) == (other.x, other.y)
def __hash__(self):
return hash((self.x, self.y))
a = Vec(3, 4)
b = Vec(1, 2)
print(a + b, a - b, 2 * a, a * 0.5)
print(-b, abs(a))
print(a == Vec(3, 4), a == (3, 4), len({a, Vec(3, 4), b}))
try:
a + 1
except TypeError as e:
print("TypeError:", e)
# ✅ Expected output:
# Vec(4, 6) Vec(2, 2) Vec(6, 8) Vec(1.5, 2.0)
# Vec(-1, -2) 5.0
# True False 2
# TypeError: unsupported operand type(s) for +: 'Vec' and 'int'__hash__ comes from the same fields as __eq__, as Magic Methods & the Python Data Model showed, which is what lets a and Vec(3, 4) count once in the set. Nothing here changes a vector after it's made, so it's safe to keep one in a set.
Practice quiz
Vec's __mul__ returns NotImplemented unless n is an int or a float, and Vec has no __rmul__. What do print(Vec(3, 4) * 2) and then print(2 * Vec(3, 4)) do?
- Print Vec(6, 8) twice
- Stop with TypeError before printing anything
- Print Vec(6, 8), then stop with TypeError: unsupported operand type(s) for *: 'int' and 'Vec'
- Print Vec(6, 8), then stop with AttributeError
Answer: Print Vec(6, 8), then stop with TypeError: unsupported operand type(s) for *: 'int' and 'Vec'. Vec(3, 4) * 2 asks Vec's __mul__. 2 * Vec(3, 4) asks int first, which can't multiply by a Vec, and then Vec's __rmul__, which doesn't exist.
Money's __add__ is return Money(self.pence + other.pence), with no type check. What does Money(250) + 100 do?
- It stops with AttributeError: 'int' object has no attribute 'pence'
- It gives Money(350)
- It stops with TypeError: unsupported operand type(s) for +: 'Money' and 'int'
- It gives 350
Answer: It stops with AttributeError: 'int' object has no attribute 'pence'. __add__ runs with other = 100 and reads 100.pence. The method never returns NotImplemented, so Python never gets to say which types it can't add.
Money's __add__ returns NotImplemented for anything that isn't Money, and Money has no __radd__. What does print(sum([Money(250), Money(325)])) do?
- It prints Money(575)
- It prints 575
- It stops with AttributeError: 'int' object has no attribute 'pence'
- It stops with TypeError: unsupported operand type(s) for +: 'int' and 'Money'
Answer: It stops with TypeError: unsupported operand type(s) for +: 'int' and 'Money'. sum() starts from 0, so its first step is 0 + Money(250). int can't add a Money, and Money has no __radd__ to ask next.
Vec has __add__ and no __iadd__. After start = Vec(1, 1), pos = start and pos += Vec(2, 3), what does print(start) show?
- Vec(3, 4)
- Vec(1, 1)
- None
- It stops with TypeError: unsupported operand type(s) for +=: 'Vec' and 'Vec'
Answer: Vec(1, 1). Without __iadd__, pos += Vec(2, 3) runs pos = pos + Vec(2, 3): a new Vec for pos, while start still names the old one.
Vec's __iadd__ adds the other vector's x and y to its own, and has no return line. After pos = Vec(1, 1) and pos += Vec(2, 3), what does print(pos) show?
- Vec(3, 4)
- Vec(1, 1)
- It stops with TypeError
- None
Answer: None. Python points pos at whatever __iadd__ returns, and a function with no return line returns None.
Score has only an __lt__ that compares points. What does print(Score(70) > Score(90)) print?
- False
- It stops with TypeError: '>' not supported between instances of 'Score' and 'Score'
- True
- It stops with AttributeError
Answer: False. Score has no __gt__, so Python asks the right-hand Score the reflected question, Score(90) < Score(70), which is False.
Score has an __lt__ and an __eq__ that compare points, and no other comparison methods. What does print(Score(70) <= Score(90)) do?
- It prints True
- It stops with TypeError: '<=' not supported between instances of 'Score' and 'Score'
- It prints False
- It stops with AttributeError
Answer: It stops with TypeError: '<=' not supported between instances of 'Score' and 'Score'. Python doesn't build <= out of < and ==. functools.total_ordering would write it.
Money's __mul__ is return Money(self.amount.__mul__(n)), and Money(100) holds the int 100. What does print(Money(100) * 2.5) print?
- Money(250.0)
- It stops with TypeError: unsupported operand type(s) for *: 'int' and 'float'
- Money(NotImplemented)
- Money(250)
Answer: Money(NotImplemented). (100).__mul__(2.5) is int's own method, which can't multiply by a float and returns NotImplemented. Only the * operator would go on to ask the float.
Continue this course
- Previous: Magic Methods & the Python Data Model
- Next: Mixins, Multiple Inheritance & OOP Patterns — Compose behaviour with mixins and navigate multiple inheritance safely
- Quick reference: Python cheat sheet › Classes
Frequently asked questions
Why does pair[0] += [3] raise an error and still change the list?
+= on an item does two things: it asks the list for __iadd__, which adds 3 to the list itself, and then it stores the result back in pair[0]. If pair is the tuple ([1], [2]), the second step stops with TypeError: 'tuple' object does not support item assignment, but the list has already changed, so pair is ([1, 3], [2]) afterwards.
Which method runs first when the right-hand value is a subclass?
The subclass's reflected method, if it has one of its own, so a subclass can take an operation over from its parent. With Money's __add__ and a subclass Tip that defines __radd__, Money(250) + Tip(50) calls Tip.__radd__ and never Money.__add__, and the answer is a Tip of 300 pence.
Is there a function for each operator?
Yes, in the operator module, for places that expect a function: operator.add(2, 3) is 5, operator.lt(2, 3) is True and operator.mul("ab", 2) is "abab". They ask the same special methods the operators do. The operator Module covers them.
How do I make round() work on my class?
Write __round__(self, ndigits=None), which round() calls. A Money whose __round__ returns Money(round(self.pence, -2)), rounding to whole pounds, gives Money(300) for round(Money(275)) and Money(200) for round(Money(249)).
What is the @ operator for?
Matrix multiplication. Python's own number types don't use it: 2 @ 3 stops with TypeError: unsupported operand type(s) for @: 'int' and 'int'. NumPy does, and your class can through __matmul__: a Vec whose __matmul__ returns the dot product gives 11 for Vec(1, 2) @ Vec(3, 4).
Why does cart += "jam" work when cart + "jam" doesn't?
A list's __iadd__ accepts any iterable, as extend() does, and a string is an iterable of letters, so a cart of ["tea"] becomes ['tea', 'j', 'a', 'm']. A list's + only accepts another list: ["tea"] + "jam" stops with TypeError: can only concatenate list (not "str") to list.
Why does my class get "can't multiply sequence by non-int"?
Because your __mul__ returned NotImplemented, so Python asked the other value, and a string's reflected * has its own error. With this lesson's checked Vec, Vec(1, 2) * "2" stops with TypeError: can't multiply sequence by non-int of type 'Vec'.
Can mypy catch Money(250) + 100 before the program runs?
Yes, if __add__'s hint names the type it accepts. With def __add__(self, other: "Money") -> "Money", mypy 1.19.1 reports error: Unsupported operand types for + ("Money" and "int") on the line that adds 100, and it accepts the isinstance() check and the return NotImplemented inside. Keep the check, since hints aren't checked while the program runs. With other: object, mypy accepts the line, because an int is an object. Type Hints & Static Typing with mypy shows how to run mypy.