Python · Level 3 OOP

Magic Methods

Teach your own classes to work with +, == and print() by defining __add__, __eq__ and __repr__.

  • __repr__ controls how an object prints
  • __eq__ powers ==
  • __add__ powers +

Python calls special dunder methods behind operators: a + b runs a.__add__(b), a == b runs a.__eq__(b), and repr(a) runs a.__repr__().

class Point:
    def __init__(self, x):
        self.x = x
    def __add__(self, other):
        return Point(self.x + other.x)
    def __repr__(self):
        return f"Point({self.x})"

Point(1) + Point(2)   # Point(3)

Give Money an __add__ that returns a new Money, an __eq__ that compares amounts, and a __repr__ like Money(12).

solution.py
Test Suites Pending
Stdout