Learn Python
>>> oop_advanced.magic_methods

Magic / Dunder Methods in Python

#concept

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.

#how it works
1

Dunder names are fixed by Python

__str__, __len__, __eq__, and others — the double underscores signal they’re meant to be called by Python itself.

2

Defining one hooks into built-in syntax

An instance starts responding correctly to the matching syntax or function.

3

__str__(self) controls display

What str(instance) and print(instance) actually show.

4

__len__(self) controls len()

What len(instance) returns.

5

__eq__(self, other) controls ==

What instance == other actually checks.

#example
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))
Output
Playlist with 3 songs
3
1print(p) doesn’t print a generic object representation — it calls __str__(self) automatically and shows that returned string instead.
2len(p) doesn’t fail with a TypeError, even though Playlist isn’t a built-in sequence — it calls __len__(self), which was defined to delegate to the underlying songs list.
3Both built-in functions behave exactly as they would for a real list or string, because Playlist implements the matching dunder methods.
#use cases
Making a custom class print nicely with __str__, instead of a default, unhelpful memory address
Letting a custom collection class work naturally with len(), for x in ..., and indexing, by implementing the matching dunders
Supporting == comparisons between instances with __eq__, instead of the default identity-only comparison
Building a class that behaves like a built-in type, integrating smoothly with the rest of the language's syntax

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.