Lesson 51 of 60
โฎPrev Nextโฏ

PY-101 ยท Object-oriented Python

Dunder methods

โฑ 8 min ๐Ÿ Real Python 3 ๐ŸŽฌ Animated

51of 60

Your note

My notes for this lesson

Select any text in the lesson to highlight it or add a note. Saved in this browser.

    No highlights yet. Select a sentence in the lesson, then pick a colour or add a note.

    All my bookmarks and notes

    Reading settings

    For every lesson, saved in this browser.

    Text size
    Line spacing
    Font

    With IaaS you rent the virtual machine. Microsoft looks after the building, power and hardware; you patch the operating system.

    โšก 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.

    Dunder methods, running
    1. class Money:
    2. def __init__(self, amount):
    3. self.amount = amount
    4. def __str__(self):
    5. return f"โ‚น{self.amount:,}"
    6. def __repr__(self):
    7. return f"Money({self.amount})"
    8. def __add__(self, other):
    9. return Money(self.amount + other.amount)
    10. def __eq__(self, other):
    11. return self.amount == other.amount
    12. def __lt__(self, other):
    13. return self.amount < other.amount
    14. a, b = Money(1500), Money(250)
    15. print(a + b)
    16. print(a == Money(1500))
    17. print(sorted([a, b, Money(900)]))
    Press โ–ถ to watch Python run this, one line at a time.
    1. The problemprint(order) shows <__main__.Order object at 0x10...>, which helps nobody. One __str__ method and it shows "Order #42: 3 items, โ‚น540".
    2. The Python ideadef __str__(self): ...Dunder methods are special methods with double underscores, like __str__ or __eq__, that Python calls for you in certain situations.
    3. 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): ...

    โ–ถ Run the example ๐ŸŽฌ Watch it come alive

    Real-world scenario

    pandas DataFrames print as neat tables and support + and == column by column, all through dunder methods.

    Ready for more?The full lesson adds the technical explanation, interview questions and quick revision.

    Test yourself

    5 questions. Get 4 right and this lesson is marked complete.

    1. 1. Which method does print(obj) use?
    2. 2. a == b calls?
    3. 3. What makes sorted() work on your objects?
    4. 4. What does dunder stand for?
    5. 5. __repr__ is mainly for?

    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