Python Tutorial: Dunder Methods
Make your classes feel like built-ins. __str__, __repr__, __len__, __eq__, and operator overloading.
Make your class behave like Python
Why does `print(myList)` work nicely? Why can you use `len(myList)`? Why can you compare two strings with `==`?
Dunder methods (double underscore methods) are the hooks Python uses internally. Add them to your class and it starts feeling like a first-class Python citizen. Twelve steps.
What you'll learn in this Python dunder methods tutorial
This interactive Python tutorial has 8 hands-on exercises. Estimated time: 20 minutes.
- Python's secret hooks — Have you ever wondered how `print(myList)` knows to show `[1, 2, 3]`? Or how `len(myList)` knows the count?
- __str__ vs __repr__ — Two methods, two purposes:
- __len__ — make len() work — `len(obj)` calls `obj.__len__()`. Add it to your class and len() just works.
- __eq__ — make == work properly — By default, `==` on objects checks memory address — two different objects are never equal, even with identical data.
- __lt__ — make sorting work — Want to use `sorted()` on a list of your custom objects? You need `__lt__` (less than).
- __add__ — overload the + operator — `v1 + v2` calls `v1.__add__(v2)`. Implement it and the + operator works on your class.
- __contains__ — make 'in' work — `x in obj` calls `obj.__contains__(x)`. Add it to your class and the `in` keyword just works.
- Build a Money class — Final challenge — no starter code.
Python Dunder Methods concepts covered
- Make your class behave like Python