Full answer
class Cart:
def __init__(self, items=()):
self.items = list(items)
def __len__(self):
return len(self.items)
def __add__(self, other):
if not isinstance(other, Cart):
return NotImplemented
return Cart(self.items + other.items)
def __eq__(self, other):
return isinstance(other, Cart) and self.items == other.items
def __iter__(self):
return iter(self.items)
a, b = Cart(["pen"]), Cart(["book", "bag"])
c = a + b
print(len(c), list(c), c == Cart(["pen", "book", "bag"]))
try:
a + 5
except TypeError as e:
print("TypeError:", e)
print(Cart.__hash__)Output:
3 ['pen', 'book', 'bag'] True
TypeError: unsupported operand type(s) for +: 'Cart' and 'int'
Nonelen(cart) calls __len__, cart + other calls __add__, == calls __eq__ and the for loop calls __iter__. Adding a plain number returns NotImplemented, so Python tries int.__radd__, finds no support either and raises TypeError, which is the correct behaviour instead of a confusing error from inside the method.
Defining __eq__ sets __hash__ to None, which makes instances unhashable unless __hash__ is also defined; the last line shows that. This protects sets and dicts from objects whose equality changes.
Common groups: __repr__/__str__ for display, __getitem__/__contains__ for containers, __enter__/__exit__ for context managers, __call__ for callables, and rich comparisons (__lt__ and friends, or functools.total_ordering).
class Cart:
def __init__(self, items=()):
self.items = list(items)
def __len__(self):
return len(self.items)
def __add__(self, other):
if not isinstance(other, Cart):
return NotImplemented
return Cart(self.items + other.items)
def __eq__(self, other):
return isinstance(other, Cart) and self.items == other.items
def __iter__(self):
return iter(self.items)
a, b = Cart(["pen"]), Cart(["book", "bag"])
c = a + b
print(len(c), list(c), c == Cart(["pen", "book", "bag"]))
try:
a + 5
except TypeError as e:
print("TypeError:", e)
print(Cart.__hash__)Run on Python 3.13.5, twice in fresh interpreters, with identical output.
Key points
- Dunders hook into built-in operations
- Return NotImplemented for unsupported operands
- __eq__ without __hash__ makes objects unhashable
- Iteration uses __iter__
- total_ordering fills comparisons
Common mistakes
- Raising TypeError directly instead of returning NotImplemented
- Defining __eq__ and expecting objects to stay hashable
Follow-ups
- When should __hash__ be defined?
- How does __getitem__ alone make a class iterable?
Tips
- Show NotImplemented