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
Foundation builder
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 / 4Step 1
__init__, __repr__, __str__.
Apply this step while implementing dunder (magic) methods in real code.
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.
Hands-on exercise
Interview preparation — practice these questions:
- Difference between __str__ and __repr__?
- When add __hash__?
- What are protocols in Python?
Summary
In summary: Dunders = duck-typed protocols. dataclasses auto-generate many.
Ready to mark this lesson complete?Track your journey across the entire course.