Teaching Python about your objects
Print a Player right now and you get noise like <__main__.Player object at 0x102f4b0>. Compare two equal-looking players with == and you get False. Python does not know what your class means yet.
You teach it with dunder methods (double-underscore, like __init__). Python calls them for you at the right moments:
| You write | Python calls |
|---|---|
print(p) or repr(p) | p.__repr__() |
p == q | p.__eq__(q) |
len(p) | p.__len__() |
p + q | p.__add__(q) |
__repr__ should return a string that looks like the code to rebuild the object, like Player('mia', 50). It makes debugging and printing lists of objects dramatically nicer.
Dunder methods are the reason built-in types feel seamless: len(text), a + b, x == y all route through them. Implementing the same hooks is how your classes plug into that machinery instead of fighting it.
Code exercise · python
Run this program. With __repr__ and __eq__ defined, printing is readable and == compares values instead of identity.
Code exercise · python
Run this program. Defining __add__ makes + work on your own type, and even sum() joins in, because sum simply applies + repeatedly (the Money(0) argument tells it what to start from). Note that __add__ returns a NEW Money instead of modifying either operand.
Code exercise · python
Your turn. Give Playlist a __len__ that returns how many songs it holds, and a __repr__ like Playlist('road trip', 2 songs). Then the two prints below will work.
Quiz
Without a custom __eq__, what does Point(2, 3) == Point(2, 3) return?