PY-101 ยท Object-oriented Python
Dunder methods
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
Dunder methods are special methods with double underscores, like __str__ or __eq__, that Python calls for you in certain situations. Define __str__ and print(obj) shows something readable; define __eq__ and == compares your objects; define __len__ and len(obj) works. They make your own classes behave like built-in types.
- Control printing with __str__ and __repr__
- Compare with __eq__ and __lt__
- Support len() and + with __len__ and __add__
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
class Money:def __init__(self, amount):self.amount = amountdef __str__(self):return f"โน{self.amount:,}"def __repr__(self):return f"Money({self.amount})"def __add__(self, other):return Money(self.amount + other.amount)def __eq__(self, other):return self.amount == other.amountdef __lt__(self, other):return self.amount < other.amounta, b = Money(1500), Money(250)print(a + b)print(a == Money(1500))print(sorted([a, b, Money(900)]))
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
โน1,750
True
[Money(250), Money(900), Money(1500)] ๐ฏ Give Playlist a __len__ that returns the number of songs, and a __str__ that returns "Playlist (3 songs)". Print len(p) and then p.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
def __len__(self): return len(self.songs); def __str__(self): return f"Playlist ({len(self)} songs)"
- The problemprint(order) shows <__main__.Order object at 0x10...>, which helps nobody. One __str__ method and it shows "Order #42: 3 items, โน540".
- The Python idea
def __str__(self): ...Dunder methods are special methods with double underscores, like __str__ or __eq__, that Python calls for you in certain situations. - In real lifepandas DataFrames print as neat tables and support + and == column by column, all through dunder methods.
Start with a question
print(order) shows <__main__.Order object at 0x10...>, which helps nobody. One __str__ method and it shows "Order #42: 3 items, โน540".
Well-designed classes print nicely, compare correctly and sort naturally. Dunder methods are how.
Explain it like I'm 10
Dunder methods are secret handshakes. When Python sees print, == or +, it looks for the matching handshake on your object.
The technical explanation
print(obj) and str(obj) call __str__; the console and lists show __repr__.
a == b calls a.__eq__(b); a < b calls __lt__, which also makes sorted() work.
len(obj) calls __len__; a + b calls __add__.
Syntax
def __str__(self): ...
def __eq__(self, other): ...
def __len__(self): ... Real-world scenario
pandas DataFrames print as neat tables and support + and == column by column, all through dunder methods.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: Dataclasses โQuestions people ask
What is the difference between __str__ and __repr__?
__str__ is the friendly text for users (print). __repr__ is the precise text for developers (console, lists, logs). If __str__ is missing, Python uses __repr__.
Why are they called magic methods?
Because Python calls them for you behind operators and built-ins like +, == and len(). "Dunder methods" is the more common name today.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between __str__ and __repr__?
__str__ is the friendly text for users (print). __repr__ is the precise text for developers (console, lists, logs). If __str__ is missing, Python uses __repr__.
beginner Why are they called magic methods?
Because Python calls them for you behind operators and built-ins like +, == and len(). "Dunder methods" is the more common name today.
intermediate Which method does print(obj) use?
__str__. print calls str(), which uses __str__.
intermediate a == b calls?
__eq__. __eq__ defines equality.
Quick revision
Remember
- Control printing with __str__ and __repr__
- Compare with __eq__ and __lt__
- Support len() and + with __len__ and __add__
- __repr__ is for developers (unambiguous, ideally looks like code); __str__ is for users (friendly). If you write only one, write __repr__.
Syntax
def __str__(self): ...
def __eq__(self, other): ...
def __len__(self): ... Official documentation
- Special method names (docs.python.org)