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__`.
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.