Reading — step 1 of 7
Learn
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
At minimum implement __repr__. Python falls back to __repr__ when __str__ is missing.
Arithmetic — __add__, __sub__, __mul__, __truediv__
For Vector * 3 (number on right), __mul__ works. For 3 * Vector (number on left), implement __rmul__ too.
Equality and ordering — __eq__, __lt__, etc.
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
__call__ — make instances callable
Useful for stateful function-like objects.
__enter__ / __exit__ — context managers
Make your class work with with:
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 bereturn Vector(...), notself.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…