Skip to content
Special Methods
step 1/7

Reading — step 1 of 7

Learn

~3 min readObject-Oriented Programming

You write print(my_obj) and get a cryptic <__main__.Foo object at 0x7fa>. You try my_a + my_b and get a TypeError. You call len(my_collection) and Python complains. Your objects feel like second-class citizens.

The reason: built-in types implement special methods (also called dunder methods — short for "double-underscore"). When Python sees a + b, it calls a.__add__(b). When it sees len(x), it calls x.__len__(). By implementing the same dunder methods in your own classes, your objects become first-class citizens of Python.

__repr__ and __str__ — text representation

python

At minimum implement __repr__. Python falls back to __repr__ when __str__ is missing.

Arithmetic — __add__, __sub__, __mul__, __truediv__

python

For Vector * 3 (number on right), __mul__ works. For 3 * Vector (number on left), implement __rmul__ too.

Equality and ordering — __eq__, __lt__, etc.

python

With __eq__ and __lt__, you can use ==, <, sort lists of vectors, etc. The functools.total_ordering decorator fills in <=, >, >= automatically given __eq__ and __lt__.

Important: defining __eq__ automatically sets __hash__ to None, making your objects unhashable — they can't go in sets or dict keys. If you need that, also implement __hash__, hashing the same fields __eq__ compares.

__len__, __getitem__, __contains__ — collection-like behavior

python

__call__ — make instances callable

python

Useful for stateful function-like objects.

__enter__ / __exit__ — context managers

Make your class work with with:

python

Built-in open() uses this pattern — with open(...) automatically closes the file.

The full list (approx)

There are dozens. The most useful for everyday classes:

  • __init__, __repr__, __str__
  • __eq__, __hash__, __lt__
  • __add__, __sub__, __mul__
  • __len__, __getitem__, __contains__, __iter__
  • __call__
  • __enter__, __exit__

Don't memorize them all. Look up what you need when you need it.

Common mistakes

  • Implementing __eq__ without __hash__ — your objects silently can't go in sets/dicts.
  • __add__ that doesn't return a new object — should be return Vector(...), not self.x += other.x.
  • Confusing __str__ and __repr__: str for users (print), repr for developers (interactive shell, debugger).

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…