How do you make your own class work with +, len() and indexing in Python?
Implement the matching dunder methods: __add__ for +, __len__ for len(), and __getitem__ for obj[i]. Python translates the syntax into calls to these methods, so no inheritance from built-in types is needed.
Explain it simply
When you write a + b, Python quietly runs a.__add__(b). If your class has that method, the operator works. It is like a cricket scoreboard: write "Team A + Team B" and the board knows how to add overs and runs if someone has defined what adding means.
Example
class Bill:
def __init__(self, items):
self.items = list(items)
def __add__(self, other):
return Bill(self.items + other.items)
def __len__(self):
return len(self.items)
def __getitem__(self, i):
return self.items[i]
def __contains__(self, item):
return item in self.items
b1 = Bill(["tea", "samosa"])
b2 = Bill(["vada pav"])
total = b1 + b2
print(len(total)) # Output: 3
print(total[2]) # Output: vada pav
print("tea" in total) # Output: True
print([x for x in total]) # Output: ['tea', 'samosa', 'vada pav']Because __getitem__ accepts integers starting from 0, Python can even loop over the object without __iter__.
What to say in the interview
"Operators and built-ins map to dunder methods: + to __add__, == to __eq__, len() to __len__, indexing to __getitem__, in to __contains__. I implement the ones that make sense and return NotImplemented for unsupported operand types so Python can try the other operand's method."
Common mistakes
- Making
__add__modify and returnself, surprising callers who expect a new object.