High School Computer Science · Grades 10–12
23Classes and Objects
A date is three numbers: a year, a month, a day. But adding one day to 28 February is not adding one to the third number: it gives 29 February or 1 March, depending on the year, and 31 December gives a new year. A date is three numbers and the rules that go with them. If the numbers travel through a program without their rules, sooner or later some function forgets one, and the 30th of February appears.
Python lets a program define its own kinds of values, which carry their data and the functions that respect their rules together. This chapter defines such classes, protects their rules, gives them the operators of the language, derives one class from another, and closes on the different styles in which the same program can be written.
You already know
A module offers an interface and hides its implementation (chapter 20). A list is mutable: two names can refer to the same list (chapter 2). The town library’s loans table (chapter 7).
23.1 Grouping data with the functions that act on it
Definition 23.1 (Class, instance, attribute, method)
A class is a new type of value, defined by the program. A value of that type is an instance of the class, also called an object. Each instance holds named values, its attributes; the functions defined in the class, which act on an instance, are its methods.
Definition 23.2 (Constructor)
The constructor of a class is the method that gives a new instance its first attributes. In Python it is named __init__, and it runs when the class is called: Point(3, 4).
A method receives the instance it acts on as its first parameter, by convention named self: a.distance_to(b) is the call Point.distance_to(a, b).
import math
class Point:
"""A point of the plane."""
def __init__(self, x, y): # the constructor: sets the attributes
self.x = x
self.y = y
def distance_to(self, other):
return math.hypot(self.x - other.x, self.y - other.y)
def move(self, dx, dy):
self.x += dx
self.y += dy
a, b = Point(0, 0), Point(3, 4)
print(a.distance_to(b)) # Point.distance_to(a, b)
c = b
c.move(1, 1) # c and b are the same object
print(b.x, b.y, "| same object:", b is c)
d = Point(4, 5)
print("equal coordinates:", d.x == b.x and d.y == b.y, "| same object:", d is b)
print(type(a).__name__, isinstance(a, Point))
$ python point_class.py
5.0
4 5 | same object: True
equal coordinates: True | same object: False
Point True
c moved b: they are one object. d has the same coordinates, but is another object.b and c, refer to the same object; d is a different object with equal values.23.2 Encapsulation and the interface of a class
Definition 23.3 (Encapsulation, class invariant)
Encapsulation is keeping an object’s attributes behind its methods: users call the methods, which are the class’s interface, and leave the attributes alone. A class invariant is a property of the attributes that the constructor establishes and every method keeps.
A fraction is kept reduced, with a positive denominator: is stored as and as . The constructor reduces by the greatest common divisor (the mathematics book), and every operation builds its result through the constructor, so the invariant holds for every fraction ever made. The attributes start with an underscore: they are internal, as in a module (chapter 20).
"""Exact fractions, always reduced, with a positive denominator."""
import math
class Fraction:
def __init__(self, num, den=1):
if den == 0:
raise ZeroDivisionError("a fraction with denominator 0")
g = math.gcd(num, den)
if den < 0: # the sign goes to the numerator
g = -g
self._num = num // g # invariant: gcd(num, den) = 1 and den > 0
self._den = den // g
def numerator(self):
return self._num
def denominator(self):
return self._den
The rest of the class is a set of special methods, explained in the next section.
def __repr__(self):
return f"Fraction({self._num}, {self._den})"
def __str__(self):
return str(self._num) if self._den == 1 else f"{self._num}/{self._den}"
def __eq__(self, other):
return self._num == other._num and self._den == other._den
def __lt__(self, other):
return self._num * other._den < other._num * self._den
def __add__(self, other):
return Fraction(self._num * other._den + other._num * self._den,
self._den * other._den)
def __mul__(self, other):
return Fraction(self._num * other._num, self._den * other._den)
def __float__(self):
return self._num / self._den
from fraction import Fraction
a, b = Fraction(6, 8), Fraction(1, -3)
print(a, b, repr(a))
print(a + b, a * b, a + b == Fraction(5, 12))
print(sorted([Fraction(2, 3), Fraction(1, 2), Fraction(3, 5)]))
print(float(Fraction(1, 3)), Fraction(10, 5))
try:
Fraction(1, 0)
except ZeroDivisionError as error:
print("ZeroDivisionError:", error)
$ python use_fraction.py
3/4 -1/3 Fraction(3, 4)
5/12 -1/4 True
[Fraction(1, 2), Fraction(3, 5), Fraction(2, 3)]
0.3333333333333333 2
ZeroDivisionError: a fraction with denominator 0
The class Date keeps a stronger invariant: its three numbers always form a real date. The constructor refuses anything else, and next_day handles the month and year changes in one place.
"""Dates of the calendar, always valid."""
def is_leap(year):
return year % 4 == 0 and (year % 100 != 0 or year % 400 == 0)
def days_in_month(year, month):
if month == 2:
return 29 if is_leap(year) else 28
return 30 if month in (4, 6, 9, 11) else 31
class Date:
def __init__(self, year, month, day):
if not (1 <= month <= 12 and 1 <= day <= days_in_month(year, month)):
raise ValueError(f"no such date: {year}-{month}-{day}")
self._ymd = (year, month, day) # invariant: a real date
def __str__(self):
return "{:04}-{:02}-{:02}".format(*self._ymd)
def __eq__(self, other):
return self._ymd == other._ymd
def __lt__(self, other):
return self._ymd < other._ymd # tuples compare year first
def next_day(self):
year, month, day = self._ymd
if day < days_in_month(year, month):
return Date(year, month, day + 1)
if month < 12:
return Date(year, month + 1, 1)
return Date(year + 1, 1, 1)
from date_class import Date
for d in [Date(2026, 3, 14), Date(2028, 2, 28), Date(2027, 2, 28), Date(2026, 12, 31)]:
print(d, "->", d.next_day())
print(Date(2026, 1, 31) < Date(2026, 2, 1), Date(2026, 5, 1) == Date(2026, 5, 1))
for bad in [(2027, 2, 29), (2026, 13, 1), (2026, 4, 31)]:
try:
Date(*bad)
except ValueError as error:
print("ValueError:", error)
Date: four days after, two comparisons, three impossible dates. code/grade-12/02-classes-and-objects/listings/use_date.py$ python use_date.py
2026-03-14 -> 2026-03-15
2028-02-28 -> 2028-02-29
2027-02-28 -> 2027-03-01
2026-12-31 -> 2027-01-01
True True
ValueError: no such date: 2027-2-29
ValueError: no such date: 2026-13-1
ValueError: no such date: 2026-4-31
Python does not lock the attributes. A program that writes into _num breaks the invariant, and with it the methods that rely on it.
from fraction import Fraction
half = Fraction(1, 2)
half._num = 2 # reaching inside: the invariant is broken
print(half, "| equal to 1?", half == Fraction(1, 1))
print("half + half =", half + half)
$ python bad_mutation.py
2/2 | equal to 1? False
half + half = 2
__eq__ assumed the invariant.Remark 23.4
Python also offers properties: an attribute that is read like f.numerator but computed by a method, which can refuse to be written. They let a class change how it stores its data without changing how users read it.
23.3 Special methods
Definition 23.5 (Special method)
A special method is a method with a name of the form __name__ that Python calls by itself for an operation of the language: __add__ for +, __eq__ for ==, __lt__ for <, __len__ for len, __str__ for str and print, __repr__ for the form shown in lists and for programmers.
class Duration:
"""A length of time, in whole minutes."""
def __init__(self, minutes):
self.minutes = minutes
def __repr__(self): # for programmers: how to rebuild it
return f"Duration({self.minutes})"
def __str__(self): # for people
return f"{self.minutes // 60} h {self.minutes % 60:02}"
def __eq__(self, other):
return self.minutes == other.minutes
def __lt__(self, other):
return self.minutes < other.minutes
def __add__(self, other):
return Duration(self.minutes + other.minutes)
class Playlist:
def __init__(self, name, durations):
self.name, self.durations = name, list(durations)
def __len__(self):
return len(self.durations)
songs = [Duration(4), Duration(71), Duration(12)]
print(songs, "|", songs[1])
print(sorted(songs), max(songs), Duration(4) == Duration(4))
print(sum(songs, Duration(0)))
print(len(Playlist("morning", songs)))
$ python special_methods.py
[Duration(4), Duration(71), Duration(12)] | 1 h 11
[Duration(4), Duration(12), Duration(71)] 1 h 11 True
1 h 27
3
repr, print shows str; sorted and max use <; sum uses +.23.4 Inheritance, a first look
Definition 23.6 (Inheritance, subclass, overriding)
A subclass is a class defined from another, its base class, by inheritance: it has all the base class’s methods, and may add others. A method of the subclass with the same name as one of the base class overrides it: it replaces it for the instances of the subclass.
import math
class Shape:
def area(self):
raise NotImplementedError("each kind of shape gives its own area")
def describe(self): # inherited by every subclass
return f"{type(self).__name__} of area {self.area():.2f}"
class Rectangle(Shape):
def __init__(self, width, height):
self.width, self.height = width, height
def area(self): # overrides Shape.area
return self.width * self.height
class Square(Rectangle):
def __init__(self, side):
super().__init__(side, side) # the constructor of Rectangle
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
for shape in [Rectangle(3, 2), Square(4), Circle(1)]:
print(shape.describe(), "| a Rectangle?", isinstance(shape, Rectangle))
super(). code/grade-12/02-classes-and-objects/listings/shapes.py$ python shapes.py
Rectangle of area 6.00 | a Rectangle? True
Square of area 16.00 | a Rectangle? True
Circle of area 3.14 | a Rectangle? False
describe is written once and calls the right area for each shape; a square is a rectangle.shapes.py. An arrow goes from a subclass to its base class. describe is inherited by all; area is overridden; Square only changes the constructor, through super().Inheritance suits an “is a” relation: a square is a rectangle. It is a poor tool for sharing code between classes that are not of the same kind; then an object that holds another (a playlist holds durations) is clearer.
23.5 Programming paradigms
Definition 23.7 (Programming paradigm)
A programming paradigm is a style of writing programs. In the imperative style, a program is a sequence of instructions that change variables. In the functional style, it is built from functions applied to values, without changing variables. In the object style, it is organised around objects that hold data and the methods acting on it.
Definition 23.8 (Pure function)
A pure function is a function whose result depends only on its arguments and which changes nothing outside itself: no global variable, no attribute, no printing, no file.
The town library wants the total number of days late over the loans returned after their due date. The same program three times:
"""Total days late over the loans returned after their due date, three ways."""
import csv
from datetime import date
with open("loans.csv", newline="") as f:
LOANS = list(csv.DictReader(f))
def days(a, b):
return (date.fromisoformat(b) - date.fromisoformat(a)).days
def is_late(loan):
return loan["return_date"] != "" and loan["return_date"] > loan["due_date"]
# imperative: a variable changed step by step
total = 0
for loan in LOANS:
if is_late(loan):
total += days(loan["due_date"], loan["return_date"])
print("imperative:", total)
# functional: functions applied to whole sequences, no variable changed
lateness = map(lambda x: days(x["due_date"], x["return_date"]), filter(is_late, LOANS))
print("functional:", sum(lateness))
# object: each loan knows how late it is
class Loan:
def __init__(self, row):
self.due, self.returned = row["due_date"], row["return_date"]
def days_late(self):
if self.returned != "" and self.returned > self.due:
return days(self.due, self.returned)
return 0
print("object:", sum(Loan(row).days_late() for row in LOANS))
$ python paradigms.py
imperative: 1371
functional: 1371
object: 1371
sum, and the methods of a class are often written imperatively.Each style has its field. The functional style makes programs easy to test and to run in parallel, since pure functions cannot disturb one another. The object style suits programs with many kinds of things, each with its own rules: windows and buttons, accounts, the pieces of a game. The imperative style is the closest to the machine, and often the most direct for a short computation.
23.6 Exercises
Exercise 23.1 ★
What does print(Point(1, 2)) show, with the class of the chapter? How can it be made to show (1, 2)?
Solution
Solution of Exercise 23.1.
Something like <__main__.Point object at 0x7f3a...>: the class name and a memory address, which changes from run to run. Defining a special method gives a readable form:
def __repr__(self):
return f"({self.x}, {self.y})"
Without __str__, print uses __repr__.
Exercise 23.2 ★
After a = Fraction(1, 2), b = a + Fraction(1, 4) and c = b * Fraction(2, 3), what do print(b, c) and print(repr(c)) show?
Solution
Solution of Exercise 23.2.
and : print(b, c) shows 3/4 1/2, and print(repr(c)) shows Fraction(1, 2).
Exercise 23.3 ★
Write a class Tally with a method add(k=1), which adds k to a count starting at , and a method value().
Solution
Solution of Exercise 23.3.
class Tally:
def __init__(self):
self._count = 0
def add(self, k=1):
self._count += k
def value(self):
return self._count
Exercise 23.4 ★
p = Point(1, 2), q = p, q.move(2, 0), r = Point(p.x, p.y), r.move(0, 1). Give the coordinates of p, q and r.
Solution
Solution of Exercise 23.4.
p and q are one object, moved once: both are at . r is a new object built from those values, then moved: ; moving it changed neither p nor q.
Exercise 23.5 ★
A student writes def move(dx, dy): in the class Point. The call p.move(1, 1) raises TypeError: Point.move() takes 2 positional arguments but 3 were given. Explain the three.
Solution
Solution of Exercise 23.5.
p.move(1, 1) is the call Point.move(p, 1, 1): three arguments, the object and the two numbers. The method was written with two parameters, as if Python did not pass the object. The repair is def move(self, dx, dy):; without it, even the body could not name the object it should change.
Exercise 23.6 ★★
Write sub(a, b), the difference of two fractions, using only the interface of Fraction. Why is the result reduced without any work of yours?
Solution
Solution of Exercise 23.6.
def sub(a, b):
num = a.numerator() * b.denominator() - b.numerator() * a.denominator()
return Fraction(num, a.denominator() * b.denominator())
The result is built by the constructor, which reduces it: the invariant is the class’s work, not the user’s. sub(Fraction(1, 2), Fraction(1, 3)) is 1/6.
Exercise 23.7 ★★
{Fraction(1, 2)} raises TypeError: unhashable type: 'Fraction'. Why can an object with __eq__ not go into a set, until the class also defines __hash__?
Solution
Solution of Exercise 23.7.
A set finds its elements by their hash, and equal elements must have equal hashes, or two equal fractions could sit in two places of the same set. The hash Python gives every object by default comes from its identity: two equal fractions, being two objects, would get different hashes. So a class that defines __eq__ loses that default, and its objects are refused by sets and as dictionary keys until it defines __hash__ from the values it compares, for example return hash((self._num, self._den)). This is only safe because no method changes a fraction once built.
Exercise 23.8 ★★
A.__init__ prints A. B(A) has an __init__ that prints B in, calls super().__init__(), then prints B out. What does B() print? And without the call to super()?
Solution
Solution of Exercise 23.8.
B in, A, B out: super().__init__() runs the constructor of A in the middle of that of B. Without the call, B in and B out only: the constructor of A never runs, and any attribute it would have set is missing from the object.
Exercise 23.9 ★★
Write a method previous_day for the class Date, and check it on 1 March 2028 and 1 January 2027.
Solution
Solution of Exercise 23.9.
def previous_day(self):
year, month, day = self._ymd
if day > 1:
return Date(year, month, day - 1)
if month > 1:
return Date(year, month - 1, days_in_month(year, month - 1))
return Date(year - 1, 12, 31)
1 March 2028 gives 2028-02-29, a leap year; 1 January 2027 gives 2026-12-31. The tests compare the method with the calendar of the standard library on days in a row.
Exercise 23.10 ★★
Prove that every Fraction, including the results of + and *, has a positive denominator and a numerator and denominator with no common divisor other than .
Solution
Solution of Exercise 23.10.
Every fraction is made by the constructor, since + and * return Fraction(...). So it is enough to check the constructor, for any numerator and denominator . Let , positive since . The divisions and are exact, and two numbers divided by their greatest common divisor have no common divisor other than : a common divisor of and would make a common divisor of and larger than . If , both are divided by instead: the signs change, the common divisors do not, and the denominator is positive. For + and *, the denominator passed is the product of two positive denominators, never , so the constructor accepts it and the argument applies.
Exercise 23.11 ★★
Rewrite in the functional style, with filter, map and sum: total = 0, then for x in t:, if x % 2 == 0:, total += x * x.
Solution
Solution of Exercise 23.11.
total = sum(map(lambda x: x * x, filter(lambda x: x % 2 == 0, t)))
or, with a comprehension, sum(x * x for x in t if x % 2 == 0). For t = range(7): .
Exercise 23.12 ★★★
Write a class Stack with push, pop, peek, is_empty and len, where pop and peek raise IndexError on an empty stack, and tests for it.
Solution
Solution of Exercise 23.12.
class Stack:
def __init__(self):
self._items = []
def push(self, x):
self._items.append(x)
def pop(self):
if not self._items:
raise IndexError("pop from an empty stack")
return self._items.pop()
def peek(self):
if not self._items:
raise IndexError("peek at an empty stack")
return self._items[-1]
def is_empty(self):
return self._items == []
def __len__(self):
return len(self._items)
Tests: after pushing then , pop() returns , then peek() returns and len is ; a new stack is empty, and pop() on it raises IndexError (checked with assertRaises). The next chapter builds stacks without Python’s list.
Exercise 23.13 ★★★
How many Fraction objects does this program create? total = Fraction(0), then for from to , total = total + Fraction(1, k). How many are still reachable at the end?
Solution
Solution of Exercise 23.13.
Nine: Fraction(0), then at each of the four turns Fraction(1, k) and the result of +, made by __add__. At the end only one is reachable, the one named total, ; the eight others are no longer named by anything, and Python frees their memory.
Exercise 23.14 ★★★
A class Basket has the line items = [] in its body, outside any method, and a method add that appends to self.items. After a.add("pear"), the basket b also holds a pear. Explain and correct.
Solution
Solution of Exercise 23.14.
items = [] in the body of the class makes one list, an attribute of the class itself. self.items looks for an attribute of the object, finds none, and finds the class’s: every basket appends to the same list. The repair gives each object its own list in the constructor:
def __init__(self):
self.items = []
Exercise 23.15 ★★★
Write a class Polynomial built from its list of coefficients , with __add__, __mul__, and __call__ so that p(x) computes the value at x.
Solution
Solution of Exercise 23.15.
class Polynomial:
def __init__(self, coefficients):
c = list(coefficients)
while len(c) > 1 and c[-1] == 0:
c.pop()
self.c = c
def __add__(self, other):
n = max(len(self.c), len(other.c))
a = self.c + [0] * (n - len(self.c))
b = other.c + [0] * (n - len(other.c))
return Polynomial([x + y for x, y in zip(a, b)])
def __mul__(self, other):
out = [0] * (len(self.c) + len(other.c) - 1)
for i, x in enumerate(self.c):
for j, y in enumerate(other.c):
out[i + j] += x * y
return Polynomial(out)
def __call__(self, x):
result = 0
for a in reversed(self.c):
result = result * x + a
return result
The constructor drops the zero coefficients at the end, so that is stored as [1, 2]. The term times goes to . __call__ evaluates from the highest coefficient down, one multiplication per coefficient: at gives .
23.7 Problem: Exact Fractions
Problem 23.1
Weekend problem — the harmonic sums, exactly
The harmonic sums are . With the class Fraction, a program computes them exactly, compares their denominators with the least common multiple of , and measures the error of the same sums in floating point.
"""The harmonic sums 1 + 1/2 + ... + 1/n, exactly and in floating point."""
import math
from fraction import Fraction
exact, approx = Fraction(0), 0.0
for n in range(1, 1001):
exact = exact + Fraction(1, n)
approx += 1 / n
if n <= 10 or n in (15, 20):
lcm = math.lcm(*range(1, n + 1))
print(f"H{n:<2} = {str(exact):>18} lcm(1..{n}) = {lcm:>8}"
f" = {lcm // exact.denominator()} x denominator")
if n in (10, 100, 1000):
print(f" n = {n:4}: float sum {approx!r:<20} exact value {float(exact)!r:<20}"
f" error {approx - float(exact):.1e}")
print("digits of the exact numerator for n = 1000:", len(str(exact.numerator())))
$ python harmonic.py
H1 = 1 lcm(1..1) = 1 = 1 x denominator
H2 = 3/2 lcm(1..2) = 2 = 1 x denominator
H3 = 11/6 lcm(1..3) = 6 = 1 x denominator
H4 = 25/12 lcm(1..4) = 12 = 1 x denominator
H5 = 137/60 lcm(1..5) = 60 = 1 x denominator
H6 = 49/20 lcm(1..6) = 60 = 3 x denominator
H7 = 363/140 lcm(1..7) = 420 = 3 x denominator
H8 = 761/280 lcm(1..8) = 840 = 3 x denominator
H9 = 7129/2520 lcm(1..9) = 2520 = 1 x denominator
H10 = 7381/2520 lcm(1..10) = 2520 = 1 x denominator
n = 10: float sum 2.9289682539682538 exact value 2.9289682539682538 error 0.0e+00
H15 = 1195757/360360 lcm(1..15) = 360360 = 1 x denominator
H20 = 55835135/15519504 lcm(1..20) = 232792560 = 15 x denominator
n = 100: float sum 5.187377517639621 exact value 5.187377517639621 error 0.0e+00
n = 1000: float sum 7.485470860550343 exact value 7.485470860550345 error -1.8e-15
digits of the exact numerator for n = 1000: 434
Part I — A class of fractions.
- Which attributes does a
Fractionhave, and why do their names start with an underscore? - What does
Fraction(10, -4)store? - Which special method does
exact + Fraction(1, n)call, and with which arguments? - Why does
Fraction(1, 2) == Fraction(2, 4)hold, although was written? - Why does the class define
numerator()anddenominator()rather than letting users read_numand_den?
Part II — The invariant.
- State the invariant of
Fraction. - Prove that the constructor establishes it, whatever the signs of its arguments (the denominator not ).
- Show that
__eq__is right because of the invariant: two fractions are equal numbers exactly when their reduced forms are equal. - What does
bad_mutation.pyshow about Python’s protection of attributes?
Part III — The harmonic sums exactly.
- Compute by hand, and check the output.
- From the output, give and . Check .
- How many digits has the numerator of ? Why could no type of fixed size hold it?
- Why can no floating-point number hold exactly?
Part IV — Denominators and floating point.
- Why is always a common denominator of the terms of ?
- For which of the output is the reduced denominator smaller than that common multiple? By how much?
- For , write over and explain why it reduces by .
- At and , how large is the floating-point error printed? And at ?
- Where does that error come from? Recall chapter 4.
- Why is the error at so small compared with the value?
- State the result: exactly, and the error of the floating-point sum up to .
Solution
Solution of Problem 23.1.
1. _num and _den. The underscore says they are internal: users go through the methods, which keep the invariant.
2. ; the denominator is negative, so both are divided by : _num is and _den is .
3. __add__, with self the fraction named exact and other the new Fraction(1, n).
4. The constructor stored as ; __eq__ then compares with and with .
5. The methods give read access only, so that no user can break the invariant by writing; and the class stays free to store its data otherwise without changing its users.
6. The denominator is positive, and the numerator and denominator have no common divisor other than .
7. Exercise 23.10.
8. Let and be reduced, with . If they are equal numbers, . Then divides and has no common divisor with , so divides ; in the same way divides . Both being positive, , and then . Equal numbers have equal attributes, so comparing attributes is right; without the invariant, and would be found different.
9. That it does not protect them: the underscore is a convention, and any program can write half._num = 2. The invariant breaks, and __eq__, which relies on it, answers wrongly that is not .
10. , as printed.
11. and ; , and .
12. digits. A -bit integer holds at most , which has digits; Python’s integers grow as needed (chapter 3).
13. A floating-point number is a whole number of at most bits times a power of (chapter 4): its denominator is a power of . has the factor in its reduced denominator, so its binary writing never ends, and every floating-point number differs from it.
14. Each from to divides , so is the fraction with that denominator and numerator , a whole number.
15. For , and , by a factor ; for , by a factor . For the other printed values the reduced denominator is the common multiple itself.
16. , and . and : .
17. at and : the floating-point sum is the closest floating-point number to the exact value. At , .
18. Each addition rounds its result to the nearest floating-point number, and is itself rounded; the small errors of a thousand roundings mostly cancel out, but not all of them: a few units of the last place remain.
19. The value is about , so the error is about of it: two units of the last bit for numbers between and , whose spacing is . Fifteen significant digits are right.
20. exactly; summed in floating point up to , the harmonic sum is off by , about of its value .