Skip to main content
Albero Academy

Magic / Dunder Methods

Hook into Python syntax with __str__, __eq__, __len__ and friends.

Object-Oriented Programming10 min

Magic methods — "dunder" methods, for the double underscores around their names — let your own objects plug into Python's built-in syntax. By implementing them, your type can be printed, compared, added, measured with len(), and more, just like a built-in.

The ones you'll use most

DunderEnables
__init__Construction: Money(100)
__str__ / __repr__print() and the REPL display
__eq__The == operator
__lt__ / __gt__Ordering and sorting
__len__len(obj)
__add__The + operator
operator overloading
class Money:
def __init__(self, rupees):
self.rupees = rupees
def __str__(self): # user-facing: what print() shows
return f"₹{self.rupees}"
def __repr__(self): # dev-facing: unambiguous debug form
return f"Money({self.rupees})"
def __eq__(self, other): # ==
return self.rupees == other.rupees
def __add__(self, other): # +
return Money(self.rupees + other.rupees)
print(Money(100) + Money(50)) # ₹150
Money(100) == Money(100) # True

__str__ vs __repr__

Key takeaways

  1. 01Dunder methods integrate your objects with Python syntax.
  2. 02__str__ is the user-facing display; __repr__ is the developer/debug form.
  3. 03__eq__ controls ==; __lt__/__gt__ enable ordering and sorting.
  4. 04__len__, __getitem__ and __add__ enable len(), indexing and +.
  5. 05Implement only the dunders your type genuinely needs.

Finished this chapter?

Mark it complete to track your progress through Python.