Interview Q&A / Python

IntermediateQuick answer1 min readUpdated 3 Oct 2026

How do you make your own class work with +, len() and indexing in Python?

SHORT ANSWER

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

python
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 return self, surprising callers who expect a new object.

#python#oop#dunder-methods

Related questions

Practise more Python questions

Test your recall with short answers, then return to the detailed explanations when you need context.

Open Python quick answers →

Get new questions like this by email

One short email when something new and useful lands. No spam, unsubscribe in one tap.

By subscribing you agree to the Privacy Policy.