Python 3D Academyবাংলা

__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): what self + other means
  • __mul__(self, n): what self * n means
  • __radd__: what other + self means 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 Money

Games 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:

  1. __add__(self, other) builds the answer from both: Vector(self.x + other.x, self.y + other.y)
  2. __mul__(self, n) scales a step: Vector(self.x * n, self.y * n)
  3. 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) + 5 makes other the int 5, so other.a gives AttributeError: 'int' object has no attribute 'a'.
  • sum() of objects. sum([M(1), M(2)]) starts from 0, so it tries 0 + 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.a inside __add__ quietly changes the left object.
  • Forgetting return. Then a + b is None.

Quiz

  1. 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)
  2. What does Python turn a + b into?

    • a.__add__(b)
    • b.__add__(a)
    • add(a, b)
  3. 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)
  4. 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)
  5. 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

  1. Give Vector an __add__ that returns a new Vector: x parts added, y parts added.

  2. Give Money an __add__ (two amounts together) and a __mul__ (an amount times a whole number). Both return a new Money.

  3. Write a class Duration(minutes) whose + adds the minutes, and whose str() gives hours and minutes like 1h 5m.