Module 15 · Lesson 01
Special (Dunder) Methods
Make your classes behave like built-in types: __repr__ and __str__ for printing, __eq__ and ordering for comparing, __add__ and friends for arithmetic, and __len__, __getitem__, __contains__ and __iter__ for containers.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Print with repr and str
- Compare and sort your objects
- Add objects with +
- Watch + become a method call
Teach your class Python's moves
Methods with double underscores let your objects work with print, ==, +, len and for loops.
Printing
__repr__for the shell and debugging,__str__forprint().Comparing
__eq__runs for==,__lt__for<and forsorted().Arithmetic
__add__runs for+,__mul__for*, and so on.Containers
__len__,__getitem__,__contains__and__iter__make it act like a list.
Dunders everywhere
Every built-in type is built from these same methods.
- MoneyA Money class can add amounts with
+and refuse to add pounds to euros. - Game movement
pos + velocitymoves a sprite when the Vector class has__add__. - Playlists
len(playlist)andfor song in playlistneed just two small methods. - Dates
date2 - date1gives a time gap, because dates define__sub__.
Three calls in disguise
This line looks like plain Python, but each part calls one of the box's own methods. Tap each part to see which.
Part 1 of 3
__len__:len(box) calls box.__len__().
Make objects act built in
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6repr and str
print() and f-strings use __str__. A list of objects uses __repr__.
Your turn: Delete __str__. Which of the three lines change?
class Book:
def __init__(self, title, pages):
self.title = title
self.pages = pages
def __repr__(self):
return f"Book({self.title!r}, {self.pages})"
def __str__(self):
return f"{self.title}, {self.pages} pages"
b = Book("Dune", 412)
print(b)
print([b])
print(f"Reading {b}")Press Run to see what it prints.Watch + become a method call
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- class Coins:
- def __init__(self, n):
- self.n = n
- def __add__(self, other):
- return Coins(self.n + other.n)
- def __repr__(self):
- return f"Coins({self.n})"
- a = Coins(3)
- b = Coins(4)
- total = a + b
- print(total)
- print(a)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Which one does an f-string use?
class T:
def __repr__(self):
return "R"
def __str__(self):
return "S"
x = T()
print(f"{x}", repr(x))0 of 6 answered
Common dunder misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
class Thing:
def __repr__(self): return "Thing(...)" # repr(), lists, shell
def __str__(self): return "friendly" # print(), str(), f-strings
def __eq__(self, other): # ==
if not isinstance(other, Thing):
return NotImplemented
return self.key == other.key
def __hash__(self): return hash(self.key) # needed with __eq__ for sets
def __lt__(self, other): ... # <, sorted(), min(), max()
def __add__(self, other): ... # self + other
def __radd__(self, other): ... # other + self, sum()
def __mul__(self, n): ... # self * n
def __len__(self): ... # len()
def __getitem__(self, i): ... # self[i], slices
def __contains__(self, item): ... # item in self
def __iter__(self): ... # for x in self
def __bool__(self): ... # if self:
@functools.total_ordering # __eq__ + __lt__ give <= > >=Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A Money type that adds and sums
Store amounts of money as whole cents to avoid floating-point errors. Make Money print nicely, compare by value, add to other Money, and work with sum() over a list of prices.
class Money:
def __init__(self, cents):
self.cents = cents
def __repr__(self):
return f"Money({self.cents})"
def __str__(self):
return f"${self.cents // 100}.{self.cents % 100:02}"
def __eq__(self, other):
if not isinstance(other, Money):
return NotImplemented
return self.cents == other.cents
def __add__(self, other):
if not isinstance(other, Money):
return NotImplemented
return Money(self.cents + other.cents)
def __radd__(self, other):
if other == 0:
return self
return NotImplemented
coffee = Money(350)
cake = Money(425)
print(coffee + cake)
print([coffee, cake])
print(coffee == Money(350), coffee == 350)
print("Total:", sum([coffee, cake, Money(5)]))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Defining __eq__ and then using a set
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
class Tag:
def __init__(self, name):
self.name = name
def __eq__(self, other):
return self.name == other.name
print(len({Tag('a'), Tag('a')}))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Developer tools
Sorting software versions correctly
A package manager must decide which release of a library is newest. Sorting version strings as text puts 1.10.0 before 1.9.2, which is wrong. A small Version class compares the numeric parts instead, and total_ordering fills in every comparison operator.
Why Python fits
Tuples compare item by item, so (1, 10, 0) is greater than (1, 9, 2), while the strings compare character by character.
sortedandmaxonly need__lt__;>=comes from total_ordering. Adding__hash__on the same tuple keeps versions usable in a set, so the duplicate release is counted once.Pythonfrom functools import total_ordering @total_ordering class Version: def __init__(self, text): self.text = text self.parts = tuple(int(part) for part in text.split(".")) def __repr__(self): return f"Version({self.text!r})" def __eq__(self, other): if not isinstance(other, Version): return NotImplemented return self.parts == other.parts def __lt__(self, other): if not isinstance(other, Version): return NotImplemented return self.parts < other.parts def __hash__(self): return hash(self.parts) releases = ["1.9.2", "1.10.0", "1.2.11", "2.0.0", "1.10.0"] print("As text:", sorted(releases)) versions = sorted(Version(r) for r in releases) print("As versions:", versions) print("Newest:", max(versions).text) print("1.10.0 >= 1.9.2:", Version("1.10.0") >= Version("1.9.2")) print("Unique:", len(set(versions)))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Should I ever call a dunder method directly?
What is the difference between returning NotImplemented and raising NotImplementedError?
Do I need __iter__ if I already have __getitem__?
Can dataclasses write these methods for me?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 18 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.