Lesson 18 of 52Objects
Dunder Methods
Make your own classes print nicely, compare, sort, index, loop and add like built-in types.
Why does len(my_list) work but my_list.length() does not? Why can you + two strings, in a dict, and loop over a file? Python's built-in behaviour is wired through special methods with double underscores, nicknamed dunder methods ("double underscore"). Learn a dozen of them and your own classes feel as natural as list and dict. Interviewers love asking about __eq__ and __hash__ in particular.
How the magic works
When you write len(x), Python calls type(x).__len__(x). When you write a + b, it calls a.__add__(b). When you print(x), it calls x.__str__(). These are ordinary methods; the only special thing is that the language calls them for you.
| You write | Python calls |
|---|---|
repr(x), the REPL, inside lists | x.__repr__() |
str(x), print(x), f-strings | x.__str__() (falls back to __repr__) |
a == b | a.__eq__(b) |
a < b | a.__lt__(b) |
len(x) | x.__len__() |
x[i] | x.__getitem__(i) |
for item in x | x.__iter__() |
item in x | x.__contains__(item) |
a + b | a.__add__(b) |
x(...) | x.__call__(...) |
len(obj) actually do?__repr__ vs __str__
By default an object prints as something like <__main__.Point object at 0x10a3f>, which tells you nothing. Two methods fix that:
__repr__is for developers: unambiguous, ideally valid Python that recreates the object. It is what you see in the REPL, in debuggers, in logs and inside containers like lists.__str__is for end users: readable.printand f-strings use it. If you skip it, Python uses__repr__.
Press Run (⌘ Enter) to see what happens.If you only write one, write __repr__. It serves both purposes.
What does this print?
class Tag:
def __init__(self, name):
self.name = name
def __repr__(self):
return f"Tag({self.name!r})"
print([Tag("a"), Tag("b")])Equality and hashing: a contract
By default a == b on your objects compares identity: two separate objects are never equal, even with the same data. Define __eq__ to compare by value.
There is a catch. Sets and dict keys use a hash, a number computed from the value, to find things fast. The rule is: objects that are equal must have equal hashes. So when you define __eq__, Python sets __hash__ to None and your objects become unhashable, unless you also define __hash__.
Press Run (⌘ Enter) to see what happens.Return NotImplemented (a special constant, not an exception) when you do not know how to compare with the other type. Python then tries the other side and falls back to False for ==.
Only hash fields that never change. If an object's hash changes while it sits in a set, the set can no longer find it.
__eq__ on a class but not __hash__. What happens when you do {obj}?Ordering and functools.total_ordering
To use <, sorted, min and max, define __lt__. Writing all six comparisons (<, <=, >, >=, ==, !=) by hand is tedious. The functools.total_ordering class decorator fills in the rest from __eq__ plus one of them.
Press Run (⌘ Enter) to see what happens.Comparing tuples does the heavy lifting: Python compares tuples item by item, so (1, 10, 0) > (1, 9). Comparing the raw strings would put "1.10.0" before "1.9".
Containers: __len__, __getitem__, __iter__, __contains__
Implement these and your class works with len, indexing, slicing, for loops and in.
Press Run (⌘ Enter) to see what happens.Fun fact: with only __getitem__, Python can still loop over your object (it calls __getitem__(0), (1), ... until IndexError). Defining __iter__ is clearer and faster.
Match the syntax to the dunder method it calls.
Operators and callables
Operator overloading means defining what +, -, * and friends do for your type. a + b calls a.__add__(b). If that returns NotImplemented, Python tries b.__radd__(a) (the "reflected" version), which is how sum() (which starts from 0) can work with your objects.
__call__ makes an instance callable like a function. That is handy for objects that are "a function with memory".
Press Run (⌘ Enter) to see what happens.The left operand always gets the first try.
What does this print?
class V:
def __init__(self, n):
self.n = n
def __mul__(self, k):
return V(self.n * k)
try:
print((3 * V(2)).n)
except TypeError:
print("TypeError")A preview: __enter__ and __exit__
The with statement is driven by two more dunders. __enter__ runs at the start of the block, __exit__ runs at the end, even if an exception happened. That is how with open(...) always closes the file. You will build your own in the context managers lesson.
class Timer:
def __enter__(self): ... # start the clock
def __exit__(self, exc_type, exc, tb): ... # stop it, even on errorA Money value type
Write a class Money that stores an amount in whole cents (an int, to avoid float rounding) and a currency code.
Money(1050, "USD")has attributescentsandcurrency.==compares by value: same cents and same currency. Comparing with a non-MoneyreturnsFalse.- Equal objects must have equal hashes, so
Moneycan live in sets and be a dict key. a + breturns a newMoney. Adding different currencies raisesValueError.sum(wallet)works on a list ofMoney(hint:sumstarts from0, so support0 + money).repr(m)isMoney(1050, 'USD')andstr(m)is10.50 USD.
Money(250, "USD") + Money(100, "USD") # Money(350, 'USD')
str(Money(5, "EUR")) # '0.05 EUR'
len({Money(1, "USD"), Money(1, "USD")}) # 1A deck that behaves like a list
Write a class Deck that wraps a list of card names and supports Python's container syntax.
Deck(["AS", "10H", "3C"])stores the cards in order.len(deck)returns the number of cards.deck[0]returns a card, and slices likedeck[1:]return a list of cards.for card in deckloops over the cards."as" in deckis case-insensitive (Truehere).repr(deck)isDeck(3 cards).
d = Deck(["AS", "10H", "3C"])
len(d) # 3
d[-1] # "3C"
"10h" in d # True
list(d) # ["AS", "10H", "3C"]- dunder method
- A method named
__like_this__that Python calls for built-in syntax such aslen,+orin. - __repr__
- The unambiguous developer representation, used by the REPL, logs and containers.
- __eq__ / __hash__ contract
- Equal objects must have equal hashes. Defining
__eq__alone makes a class unhashable. - NotImplemented
- A constant a dunder returns to say "I cannot handle this type", letting Python try the other operand.
- total_ordering
- A
functoolsdecorator that derives all comparisons from__eq__and one of__lt__,__le__,__gt__,__ge__.