Magic / Dunder Methods in Python — a practical guide to Python dunder methods with clear examples you can reuse in real projects.
Python Tutorial Series (51/95). Prefer one article? Read the complete Python tutorial.
Short description
Dunder methods hook into Python syntax and built-ins so your classes feel native.
__str__ and __len__
class Team:
def __init__(self, members):
self.members = members
def __len__(self):
return len(self.members)
def __str__(self):
return f'Team({len(self)})'
print(len(Team(['a', 'b'])), Team(['a', 'b']))