__add__ and __mul__: your own + and *
🌍 In real life. At the market you pay a 200-taka bill and a 150-taka bill: together that's 350 taka. Three packets of tea at 50 taka each cost 150 taka. You add and multiply amounts of money, not just plain numbers.
With __add__ and __mul__, your objects can use + and * too:
a + b→a.__add__(b)a * 3→a.__mul__(3)
Each one should make and return a new object, the way 2 + 3 gives a new number and leaves 2 and 3 alone.
The idea in one sentence: __add__ and __mul__ let + and * work on your objects, and each should build and return a new object.
Its words:
- operator overloading: giving an operator a meaning for your class
__add__(self, other): whatself + othermeans__mul__(self, n): whatself * nmeans__radd__: whatother + selfmeans when the left side doesn't know how
class Money:
def __init__(self, amount):
self.amount = amount
def __add__(self, other):
return Money(self.amount + other.amount)
def __mul__(self, times):
return Money(self.amount * times)
def __str__(self):
return f"{self.amount} taka"
bill1 = Money(200)
bill2 = Money(150)
print(bill1 + bill2)
print(Money(50) * 3)
print(bill1) # still 200: + made a new MoneyGames and maps use the same idea with vectors: a step like "3 east, 1 north". Walking two steps one after the other adds them: east parts together, north parts together. Step by step:
__add__(self, other)builds the answer from both:Vector(self.x + other.x, self.y + other.y)__mul__(self, n)scales a step:Vector(self.x * n, self.y * n)- a
__repr__lets you see the result
There are more of these: __sub__ for -, __truediv__ for /. They all work the same way.
Why return a new object? a + b shouldn't change a, any more than 2 + 3 changes 2. Returning a new object keeps a and b as they were, which makes the code easy to trust.
Mistakes and edge cases.
- Adding a plain number.
M(1) + 5makesotherthe int 5, soother.agivesAttributeError: 'int' object has no attribute 'a'. - sum() of objects.
sum([M(1), M(2)])starts from 0, so it tries0 + M(1):TypeError: unsupported operand type(s) for +: 'int' and 'M'. Give a start,sum(items, M(0)), or write__radd__. - Changing self.
self.a += other.ainside__add__quietly changes the left object. - Forgetting return. Then
a + bisNone.
Quiz
What does this print?
class Score: def __init__(self, points): self.points = points def __add__(self, other): return Score(self.points + other.points) total = Score(10) + Score(15) print(total.points)What does Python turn
a + binto?- a.__add__(b)
- b.__add__(a)
- add(a, b)
What does this print?
class Vector: def __init__(self, x, y): self.x = x self.y = y def __mul__(self, n): return Vector(self.x * n, self.y * n) def __repr__(self): return f"Vector({self.x}, {self.y})" print(Vector(2, -1) * 3)What does this print?
class Money: def __init__(self, amount): self.amount = amount def __add__(self, other): return Money(self.amount + other.amount) a = Money(100) b = a + Money(20) print(a.amount, b.amount)Which line has a mistake?
class Money: def __init__(self, amount): self.amount = amount def __add__(self, other): self.amount + other.amount total = Money(5) + Money(7) print(total.amount)
Coding tasks
Give
Vectoran__add__that returns a new Vector: x parts added, y parts added.Give
Moneyan__add__(two amounts together) and a__mul__(an amount times a whole number). Both return a new Money.Write a class
Duration(minutes)whose+adds the minutes, and whosestr()gives hours and minutes like1h 5m.