Python theorytheory 0/50 · 0%
OOP · hard

41. Operator overloading and dunder methods

Customizing how objects respond to +, ==, len(), etc.

Dunder ("double underscore") methods let custom classes participate in built-in syntax like arithmetic, comparisons, iteration, and container protocols.

python
class Money:
    def __init__(self, cents):
        self.cents = cents
    def __add__(self, other):
        return Money(self.cents + other.cents)
    def __eq__(self, other):
        return self.cents == other.cents
    def __repr__(self):
        return f"Money({self.cents})"
    def __lt__(self, other):
        return self.cents < other.cents

Money(100) + Money(50)   # Money(150)
Money(100) == Money(100)  # True

Implementing `__lt__` (and optionally `functools.total_ordering` to fill in the rest) makes instances sortable with `sorted()`. `__len__` and `__getitem__` let a custom object behave like a sequence.

Check your understanding

  1. 1. Which dunder method is invoked by `a + b`?

  2. 2. What does implementing `__lt__` enable?

  3. 3. What does `functools.total_ordering` do?