Advanced·8 min·advanced · oop
Magic / Dunder Methods
Magic / Dunder Methods
Python's protocol-based design: every operator and built-in maps to a "dunder" (double-underscore) method.
The ones you'll use most
| Syntax | Method |
|---|---|
len(x) | __len__ |
x[i] | __getitem__ |
for x in y | __iter__ (or __getitem__ as fallback) |
x + y | __add__ |
x == y | __eq__ |
str(x) / print | __str__ then __repr__ |
x() | __call__ |
with x: | __enter__, __exit__ |
The principle
Implement the dunder, get the syntax for free. Your class plugs straight into all of Python.
Try it
- Implement
__eq__onVecsoVec(1,2) == Vec(1,2). - Add
__mul__to scale a vector by a number.