Magic / Dunder Methods in Python
Magic methods (also called dunder methods, for their double underscores) let a custom class hook into Python's built-in syntax and behavior — defining __init__ makes ClassName() work, __str__ controls what print() shows, __len__ makes len() work, and dozens more exist for operators, comparisons, iteration, and beyond. They're how ordinary Python syntax stays consistent across both built-in types and custom classes.
Dunder names are fixed by Python
__str__, __len__, __eq__, and others — the double underscores signal they’re meant to be called by Python itself.
Defining one hooks into built-in syntax
An instance starts responding correctly to the matching syntax or function.
__str__(self) controls display
What str(instance) and print(instance) actually show.
__len__(self) controls len()
What len(instance) returns.
__eq__(self, other) controls ==
What instance == other actually checks.
class Playlist: def __init__(self, songs): self.songs = songs def __str__(self): return f"Playlist with {len(self.songs)} songs" def __len__(self): return len(self.songs) p = Playlist(["Song A", "Song B", "Song C"])print(p)print(len(p))Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in Python yourself — building beats watching.