Skip to content
dreamcode
dreamcode
Map
Dunder methods
Lesson 46 of 77
+15 XP on finish
OBJECTSChapter 8 · Objects and Classes

Special methods

Methods wrapped in double underscores, like __init__, are special methods (people call them dunder methods). Python calls them for you: __str__ when you print an object, __repr__ for a developer view, __eq__ for ==, __add__ for + and __len__ for len(). Defining them makes your objects feel built in.

Worked example

How it reads

  • a + b really calls a.__add__(b)
  • Without __eq__, == only checks whether two names point at the same object
  • __str__ decides what print shows
Cloud tip: Define __repr__ too: it is what you see for objects inside lists and in error messages.
main.py
PYTHON
real Python, runs in your browser
Console
Run your code to see its output here.
YOUR TURN

Add __len__ and __str__ so print(len(p)) prints 3 and print(p) prints Playlist of 3 songs. Print both, in that order.

Press Run to check your work.