Magic (Dunder) Methods
Hook your own classes into Python's built-in syntax
__str__ or __eq__ that Python calls for you when you use ordinary syntax such as print(obj), a == b, len(obj), or a + b. You rarely call them by name; you define them so your objects behave like built-in types.
- explain what dunder methods are and when Python invokes them,
- give objects a readable form with
__repr__and__str__, - define value equality with
__eq__, - make
len()and truthiness work through__len__, - overload operators such as
+and*with__add__and__mul__, - reason about the trade-offs, including
NotImplementedand equality/hashing.
1. What is a dunder method?
Every time you write a + b, len(x), or print(obj), Python quietly translates that syntax into a method call on the object. Those methods have names wrapped in double underscores — __add__, __len__, __str__ — which is why Python programmers pronounce them "dunder" (double-under). They are also called special methods.
Analogy: think of dunder methods as electrical sockets in a wall. The wall (Python) already knows how to send power through a standard socket. When your class provides the matching socket — the right method name and shape — the built-in machinery plugs straight in. You do not rewire the house; you just fit the standard plug so len(), ==, and print() know what to do with your object.
The key mental model: you almost never call dunder methods directly. You write the natural syntax, and Python dispatches to the dunder for you. Writing obj.__len__() works, but the whole point is that you can just write len(obj).