Back
+15 XP
Concept

Operator Overloading: `__len__`, `__getitem__`, `__eq__`

Dunder methods teach Python's operators how to treat custom objects: `len(obj)` calls `__len__`, `obj[i]` calls `__getitem__`, and `==` calls `__eq__`.

python
class Deck:
    def __init__(self, cards):
        self._cards = cards
    def __len__(self):
        return len(self._cards)
    def __getitem__(self, i):
        return self._cards[i]

d = Deck(["Ace", "King"])
print(len(d))  # 2
print(d[0])    # Ace

# 5. Operator Overloading: `__len__`, `__getitem__`, `__eq__` Dunder methods teach Python's operators how to treat custom objects: `len(obj)` calls `__len__`, `obj[i]` calls `__getitem__`, and `==` calls `__eq__`: ```python class Deck: def __init__(self, cards): self._cards = cards def __len__(self): return len(self._cards) def __getitem__(self, i): return self._cards[i] d = Deck(["Ace", "King"]) print(len(d)) # 2 print(d[0]) # Ace ``` This is called the Python Data Model. By hooking into existing dunder protocols, your custom classes feel and behave like native Python built-ins.

Checkpoint

Implementing `__getitem__` on a class automatically enables which Python features?

Practice

Implement `__eq__` on class `Box(size)` so two boxes are equal if `self.size == other.size`. Test `Box(10) == Box(10)` and print the boolean.

Terminal
01
Tap code blocks below to assemble
Available Blocks