Python Fundamentals ยท Objects, Errors and Generators

Special Methods: __add__, __eq__, __repr__

Make your own objects work with +, == and print by defining double-underscore methods.

dunder.py

class Money:
    def __init__(self, amount):
        self.amount = amount

    def __add__(self, other):        # runs for a + b
        return Money(self.amount + other.amount)

    def __eq__(self, other):         # runs for a == b
        return self.amount == other.amount

    def __repr__(self):              # how the object is shown
        return "Money(" + str(self.amount) + ")"

a = Money(5)
b = Money(7)
total = a + b
same = total == Money(12)
print(total, same)

Step by step

  1. Python starts building the class Money. Its methods are stored, but none of them run yet.
  2. Python reads the class body: everything indented under class Money belongs to it.
  3. The method __init__ is stored in Money. It runs only when it is called on an object.
  4. The method __add__ is stored in Money. It runs only when it is called on an object.
  5. The method __eq__ is stored in Money. It runs only when it is called on an object.
  6. The method __repr__ is stored in Money. It runs only when it is called on an object.
  7. The class Money is now defined, ready to make objects from.
  8. Two Money objects.
  9. A new key amount with the value 5 is added to the Money that self points to.
  10. Two Money objects.
  11. Python calls __init__(), with self = {} and amount = 7. It gets its own names.
  12. A new key amount with the value 7 is added to the Money that self points to.
  13. __init__() has finished, so its names are gone. The value it returned, {amount: 7}, is stored in b.
  14. a + b: Python calls a.__add__(b) behind the scenes.
  15. Inside __add__: return a new Money with the sum, 12.
  16. A new key amount with the value 12 is added to the Money that self points to.
  17. __init__() has finished, so its names are gone.
  18. __add__() has finished, so its names are gone. The value it returned, {amount: 12}, is stored in total.
  19. == calls __eq__.
  20. A new key amount with the value 12 is added to the Money that self points to.
  21. Python calls __eq__(), with self = {amount: 12} and other = {amount: 12}. It gets its own names. __init__() has finished, so its names are gone.
  22. The function returns self.amount == other.amount.
  23. __eq__() has finished, so its names are gone. The value it returned, true, is stored in same.
  24. print calls __repr__ to turn the object into text.
  25. The function returns "Money(" + str(self.amount) + ")".
  26. Money(12) True. Special methods let your classes behave like built-in types.