Python Tutorial 0/52 lessons ~6 min read Lesson 27
Dunder (Magic) Methods
Dunder methods (xxx) hook into Python's protocols: len for len(), iter for loops, eq for ==, etc.
Course progress0%
Focus
8 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
Dunder methods (__xxx__) hook into Python's protocols: __len__ for len(), __iter__ for loops, __eq__ for ==, etc.
Understanding the topic
Core concepts to understand:
__init__,__repr__,__str__.__eq__,__hash__— equality.__len__,__getitem__,__iter__.__enter__/__exit__— context managers.
Syntax reference
Visual flow / code:
python
class Bag:def __init__(self, items):self.items = list(items)def __len__(self): return len(self.items)def __iter__(self): return iter(self.items)def __getitem__(self, i): return self.items[i]def __repr__(self): return f"Bag({self.items!r})"b = Bag([1, 2, 3])print(len(b)) # 3for x in b: print(x)print(b[0])print(b) # Bag([1, 2, 3])
Execution workflow
1Dunder (Magic) Methods Workflow
1 / 4__init__, __repr__, __str__
__init__, __repr__, __str__.
Real-world use
Implementing the right dunders makes your class behave like a built-in — usable in for, len, in, JSON pretty-print, etc.
Best practices
- Implement
__repr__for debuggability. __eq__+__hash__together.- Use dataclasses to auto-generate them.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionDifference between __str__ and __repr__?+
Answer
__str__ returns a readable, user-friendly string and is used by str() and print(). __repr__ returns an unambiguous developer-oriented string, ideally one that looks like valid code to recreate the object, and is used in the REPL, debuggers, and inside containers. If only __repr__ is defined, it is also used as the fallback for str(), so define __repr__ first.Follow-up
What does print([obj]) use for obj, str or repr?
2IntermediateQuestionWhen add __hash__?+
Answer
Add
__hash__ when instances should be usable as dict keys or set members and you define equality with __eq__. Note that defining __eq__ without __hash__ sets __hash__ to None, making instances unhashable. Equal objects must have equal hashes, and the hash should be based on immutable fields.Follow-up
What does @dataclass(frozen=True) do about hashing?
3AdvancedQuestionWhat are protocols in Python?+
Answer
A protocol is an informal or formal interface defined by behavior rather than inheritance, the idea behind duck typing: an object that implements
__iter__ is iterable. The special-method protocols include iteration, context managers (__enter__, __exit__), and the container protocols. Since 3.8, typing.Protocol lets type checkers verify this structural typing statically, without requiring subclassing.Follow-up
How does typing.Protocol differ from an abstract base class?
Summary
In summary: Dunders = duck-typed protocols. dataclasses auto-generate many.
Ready to mark this lesson complete?Track your journey across the entire course.