Dunder method

A special method with double underscores, like __init__ or __str__, that Python calls automatically.

A dunder method (“double-underscore”, also called a special or magic method) has a name like __init__, __str__, or __len__. You rarely call them directly; Python calls them for you when you create an object, print it, or use len().

Defining them lets your own objects behave like built-in types — print(obj) uses __str__ and len(obj) uses __len__.

Example
class Playlist:
    def __init__(self, songs):
        self.songs = songs

    def __len__(self):         # called by len()
        return len(self.songs)

    def __str__(self):         # called by print()
        return f"Playlist of {len(self)} songs"

p = Playlist(["a", "b", "c"])
print(len(p))
print(p)
Output
3
Playlist of 3 songs

Where this shows up in real Python

Dunder methods make your objects work with built-in syntax — print(), len(), for, and == all call them behind the scenes.

Commonly used Dunder method tools

  • __init__ — set up a new instance
  • __str__ / __repr__ — how the object prints
  • __len__ — make len(obj) work
  • __eq__ — define what == means
  • __iter__ / __next__ — make the object loopable

Related terms