🏗️ Classes & Objects, lesson 5 of 6
Dunder methods
Make your objects print nicely, compare, sort and work with len() and +.
11 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Printing a plain object shows something like
<__main__.Point object at 0x10a3...>. Not helpful!
Python's built-in syntax calls special dunder
(double underscore) methods behind the scenes:
print(x),str(x)→x.__str__()repr(x), items in a list →x.__repr__()len(x)→x.__len__()a == b→a.__eq__(b),a < b→a.__lt__(b)a + b→a.__add__(b)
Define them, and your objects work like built-ins.
__str__ and __repr__
__str__ is the friendly version for users;
__repr__ is the precise one for developers (used in
lists and debugging). Delete both methods to see the
default.
What does this print?
Equality and ordering. By default == only checks
whether two names point at the very same object.
Define __eq__ to compare by value. Define __lt__
and sorted(), min() and max() just work.
Sortable playing cards
Delete __eq__ and the last line prints False:
two separate objects are never equal by default.
__len__, __contains__ and __add__
With __len__, if playlist: is False for an
empty playlist, just like an empty list.
Which method does len(box) call?
A 2D vector
Add four dunder methods to Vector:
__repr__returns text likeVector(1, 2)__eq__: equal when bothxandymatch__add__returns a new Vector with the parts added__mul__returns a new Vector scaled by a number:Vector(1, 2) * 3isVector(3, 6)