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
| Dunder | Enables |
|---|---|
__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 |
class Money:def __init__(self, rupees):self.rupees = rupeesdef __str__(self): # user-facing: what print() showsreturn f"₹{self.rupees}"def __repr__(self): # dev-facing: unambiguous debug formreturn f"Money({self.rupees})"def __eq__(self, other): # ==return self.rupees == other.rupeesdef __add__(self, other): # +return Money(self.rupees + other.rupees)print(Money(100) + Money(50)) # ₹150Money(100) == Money(100) # True
__str__ vs __repr__
Key takeaways
- 01Dunder methods integrate your objects with Python syntax.
- 02__str__ is the user-facing display; __repr__ is the developer/debug form.
- 03__eq__ controls ==; __lt__/__gt__ enable ordering and sorting.
- 04__len__, __getitem__ and __add__ enable len(), indexing and +.
- 05Implement only the dunders your type genuinely needs.
