Magic Methods
Mar 29, 2026
In This Chapter
- What magic methods are and why Python uses them
- The difference between
__repr__and__str__ - How methods like
__len__,__eq__, and__iter__change object behavior - Why magic methods let custom classes participate in Python protocols
- Common interview mistakes around dunder methods
What Are Magic Methods?
Magic methods, also called dunder methods , are methods with names like __init__, __repr__, or __len__.
Python calls them automatically in specific situations:
class Box:
def __init__(self, items):
self.items = items
def __len__(self):
return len(self.items)
box = Box([1, 2, 3])
len(box) # 3You do not call box.__len__() directly in normal code. Python calls it when len(box) runs.
__repr__ vs __str__
These are two of the most commonly asked interview methods:
class User:
def __init__(self, name: str):
self.name = name
def __repr__(self) -> str:
return f"User(name={self.name!r})"
def __str__(self) -> str:
return self.name__repr__is for developers__str__is for human-friendly display
If __str__ is missing, Python falls back to __repr__.
Comparison Methods
Methods like __eq__ and __lt__ define how objects compare:
class Point:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __eq__(self, other: object) -> bool:
if not isinstance(other, Point):
return NotImplemented
return self.x == other.x and self.y == other.yReturning NotImplemented for unsupported types is the right protocol behavior.
Container and Iteration Methods
Python also uses magic methods for container behavior:
__len__forlen(obj)__contains__forx in obj__iter__forfor x in obj__getitem__forobj[key]
That is why custom classes can feel like built-in types when designed well.
Protocol Thinking
The most useful interview idea is this: magic methods let your class participate in Python's protocols.
If your object implements __iter__, it behaves like an iterable. If it implements __enter__ and __exit__, it behaves like a context manager.
This is more important than memorizing a long list of dunder names.
Key Questions
Q: What are magic methods in Python?
They are special methods with double underscores that Python calls automatically to support language features like printing, comparison, iteration, and arithmetic.
Q: What is the difference between
__repr__and__str__?
__repr__ is for developers and should ideally be unambiguous. __str__ is for human-friendly display.
Q: Why does
len(obj)work on custom classes?
Because Python checks whether the class defines __len__ and, if so, calls it.
Q: Why should
__eq__sometimes returnNotImplemented?
Because that tells Python the comparison is unsupported for that type pair, which is better than making incorrect assumptions.
Q: What is the bigger idea behind magic methods?
They let your class participate in Python protocols, so custom objects can behave like built-in objects when appropriate.