Dunder (double underscore) methods hook into Python's data model—__str__, __repr__, __len__, __eq__, and operators like __add__. They let your objects behave like built-ins.
Common dunders
class Point:
def __init__(self, x, y):
self.x, self.y = x, y
def __repr__(self):
return f"Point({self.x}, {self.y})"
def __eq__(self, other):
return isinstance(other, Point) and (self.x, self.y) == (other.x, other.y)
__str__ vs __repr__
__repr__ targets developers—ideally valid Python to recreate the object. __str__ targets users—pretty display. print uses __str__, falling back to __repr__.
Important interview questions and answers
- Q: __eq__ vs is?
A:==calls__eq__;ischecks object identity (same id in memory). - Q: Why implement __repr__?
A: Debugging and REPL clarity—shows unambiguous object state.
Self-check
- Which dunder does len(obj) call?
- What is the goal of a good __repr__?
Tip: Implement __repr__ for debugging—developers see unambiguous object state in logs.
Interview prep
- __eq__ vs is?
==value equality via __eq__;isidentity (same object id).- __repr__ vs __str__?
__repr__for developers;__str__for user-friendly display—print prefers __str__.