What Are Magic Methods (Dunder Methods) in Python?

Magic methods are special methods surrounded by double underscores (like __init__ or __str__) that let a custom class integrate with Python's built-in syntax...

Published November 21, 2026

Magic (dunder) methods are special methods with double underscores, like __init__, __str__ and __add__, that Python calls automatically to implement built-in behaviour such as printing, addition and iteration.

The concept

You never usually call them directly: str(obj) calls obj.__str__(), a + b calls a.__add__(b), len(x) calls x.__len__().

Implementing them makes your classes behave like built-in types.

Syntax → method

obj() → __call__
a + b → __add__
len(x) → __len__
x[i] → __getitem__
print(obj) → __str__

Practical examples

Vector class

class Vec:
    def __init__(self, x, y): self.x, self.y = x, y
    def __add__(self, o): return Vec(self.x + o.x, self.y + o.y)
    def __repr__(self): return f'Vec({self.x}, {self.y})'
    def __eq__(self, o): return (self.x, self.y) == (o.x, o.y)
Vec(1, 2) + Vec(3, 4)  # Vec(4, 6)

Container behaviour

class Deck:
    def __init__(self): self.cards = list(range(52))
    def __len__(self): return len(self.cards)
    def __getitem__(self, i): return self.cards[i]

Callable objects

class Adder:
    def __init__(self, n): self.n = n
    def __call__(self, x): return x + self.n
Adder(5)(3)  # 8

Common mistakes

  • Defining __eq__ without __hash__ (makes the class unhashable).
  • Calling dunders directly instead of the built-in.
  • Returning the wrong type from __str__.

Key takeaways

  • Dunders hook into Python syntax.
  • __repr__ for developers, __str__ for users.
  • Define __eq__ with __hash__.

FAQ

__str__ vs __repr__?

__str__ is readable output; __repr__ is unambiguous and used in debugging.

Are they private?

No, they are just reserved names.

More Python articles