---
title: "Classes and Objects"
book: "High School Computer Science"
subject: computer-science
language: en
chapter: 23
exercises: 15
source: https://one-course.com/books/computer-science/2/en/chapter/23-classes-and-objects
license: CC-BY-NC-SA-4.0
credit: "One Computer Science Book, One Course (one-course.com)"
---

# Chapter 23 — Classes 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](#def-g12-classes-and-objects-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](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-interface) (chapter [20](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#ch-g11-modules-and-interfaces)). A list is [mutable](https://one-course.com/books/computer-science/2/en/chapter/2-tuples-sets-and-comprehensions#def-g10-tuples-sets-comprehensions-mutable): two names can refer to the same list (chapter [2](https://one-course.com/books/computer-science/2/en/chapter/2-tuples-sets-and-comprehensions#ch-g10-tuples-sets-comprehensions)). The town library’s loans table (chapter [7](https://one-course.com/books/computer-science/2/en/chapter/7-processing-data-tables#ch-g10-data-tables)).

## 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](#def-g12-classes-and-objects-class) is the [method](#def-g12-classes-and-objects-class) that gives a new [instance](#def-g12-classes-and-objects-class) its first [attributes](#def-g12-classes-and-objects-class). In Python it is named `__init__`, and it runs when the [class](#def-g12-classes-and-objects-class) is called: `Point(3, 4)`.

A [method](#def-g12-classes-and-objects-class) receives the [instance](#def-g12-classes-and-objects-class) it acts on as its first parameter, by convention named `self`: `a.distance_to(b)` is the call `Point.distance_to(a, b)`.

```python
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))
```

***Listing 23.1.** A [class](#def-g12-classes-and-objects-class) of points, three [instances](#def-g12-classes-and-objects-class), and two names for one object. code/grade-12/02-classes-and-objects/listings/point_class.py*

```
$ python point_class.py
5.0
4 5 | same object: True
equal coordinates: True | same object: False
Point True
```

***Output 23.1.** Moving `c` moved `b`: they are one object. `d` has the same coordinates, but is another object.*

![One class, three objects. The class holds the methods once; each object holds its own attributes. Two names, b and c, refer to the same object; d is a different object with equal values.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-classes-and-objects/fig-835feaae492a.svg)

*One [class](#def-g12-classes-and-objects-class), three objects. The [class](#def-g12-classes-and-objects-class) holds the [methods](#def-g12-classes-and-objects-class) once; each object holds its own [attributes](#def-g12-classes-and-objects-class). Two names, `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](#def-g12-classes-and-objects-class) behind its [methods](#def-g12-classes-and-objects-class): users call the [methods](#def-g12-classes-and-objects-class), which are the [class](#def-g12-classes-and-objects-class)’s interface, and leave the [attributes](#def-g12-classes-and-objects-class) alone. A *class invariant* is a property of the [attributes](#def-g12-classes-and-objects-class) that the [constructor](#def-g12-classes-and-objects-constructor) establishes and every [method](#def-g12-classes-and-objects-class) keeps.

A fraction is kept reduced, with a positive denominator: $6/8$ is stored as $3/4$ and $1/(-3)$ as $-1/3$. The [constructor](#def-g12-classes-and-objects-constructor) reduces by the greatest common divisor (the mathematics book), and every operation builds its result through the [constructor](#def-g12-classes-and-objects-constructor), so the invariant holds for every fraction ever made. The [attributes](#def-g12-classes-and-objects-class) start with an underscore: they are internal, as in a module (chapter [20](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#ch-g11-modules-and-interfaces)).

```python
"""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

```

***Listing 23.2.** Fractions: the [constructor](#def-g12-classes-and-objects-constructor) establishes the invariant. code/grade-12/02-classes-and-objects/listings/fraction.py*

The rest of the [class](#def-g12-classes-and-objects-class) is a set of [special methods](#def-g12-classes-and-objects-special-method), explained in the next section.

```python
    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
```

***Listing 23.3.** Fractions: printing, comparing, adding, multiplying. code/grade-12/02-classes-and-objects/listings/fraction.py*

```python
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)
```

***Listing 23.4.** Using the [class](#def-g12-classes-and-objects-class): two fractions, their sum and product, a sort, a conversion, and a denominator $0$. code/grade-12/02-classes-and-objects/listings/use_fraction.py*

```
$ 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
```

***Output 23.2.** Every result is reduced; a denominator $0$ is refused at once.*

The [class](#def-g12-classes-and-objects-class) `Date` keeps a stronger invariant: its three numbers always form a real date. The [constructor](#def-g12-classes-and-objects-constructor) refuses anything else, and `next_day` handles the month and year changes in one place.

```python
"""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)
```

***Listing 23.5.** Dates that are always valid. code/grade-12/02-classes-and-objects/listings/date_class.py*

```python
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)
```

***Listing 23.6.** Using `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
```

***Output 23.3.** The day after four dates, two comparisons, and three dates refused.*

Python does not lock the [attributes](#def-g12-classes-and-objects-class). A program that writes into `_num` breaks the invariant, and with it the [methods](#def-g12-classes-and-objects-class) that rely on it.

```python
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)
```

***Listing 23.7.** Reaching inside an object. code/grade-12/02-classes-and-objects/listings/bad_mutation.py*

```
$ python bad_mutation.py
2/2 | equal to 1? False
half + half = 2
```

***Output 23.4.** A “fraction” $2/2$, not equal to $1$: `__eq__` assumed the invariant.*

**Remark 23.4.**

Python also offers *properties*: an [attribute](#def-g12-classes-and-objects-class) that is read like `f.numerator` but computed by a [method](#def-g12-classes-and-objects-class), which can refuse to be written. They let a [class](#def-g12-classes-and-objects-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](#def-g12-classes-and-objects-class) 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.

```python
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)))
```

***Listing 23.8.** Durations that print, compare, sort and add. code/grade-12/02-classes-and-objects/listings/special_methods.py*

```
$ 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
```

***Output 23.5.** A list shows `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](#def-g12-classes-and-objects-class) defined from another, its base [class](#def-g12-classes-and-objects-class), by *inheritance*: it has all the base [class](#def-g12-classes-and-objects-class)’s [methods](#def-g12-classes-and-objects-class), and may add others. A [method](#def-g12-classes-and-objects-class) of the subclass with the same name as one of the base [class](#def-g12-classes-and-objects-class) *overrides* it: it replaces it for the [instances](#def-g12-classes-and-objects-class) of the subclass.

```python
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))
```

***Listing 23.9.** A base [class](#def-g12-classes-and-objects-class), three subclasses, and `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
```

***Output 23.6.** `describe` is written once and calls the right `area` for each shape; a square is a rectangle.*

![The classes of 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().](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-classes-and-objects/fig-733ae94c3374.svg)

*The classes of `shapes.py`. An arrow goes from a [subclass](#def-g12-classes-and-objects-inheritance) to its base [class](#def-g12-classes-and-objects-class). `describe` is inherited by all; `area` is overridden; `Square` only changes the [constructor](#def-g12-classes-and-objects-constructor), through `super()`.*

[Inheritance](#def-g12-classes-and-objects-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](#def-g12-classes-and-objects-class) 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](#def-g12-classes-and-objects-class), 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:

```python
"""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))
```

***Listing 23.10.** Days late, imperative, functional and object. code/grade-12/02-classes-and-objects/listings/paradigms.py*

```
$ python paradigms.py
imperative: 1371
functional: 1371
object: 1371
```

***Output 23.7.** Three styles, one answer.*

![The same computation in three styles. Real programs mix them: the object version uses a functional sum, and the methods of a class are often written imperatively.](https://one-course.com/images/onecourse/chapters/computer-science-2/g12-classes-and-objects/fig-f4d0e9144c3d.svg)

*The same computation in three styles. Real programs mix them: the object version uses a functional `sum`, and the [methods](#def-g12-classes-and-objects-class) of a [class](#def-g12-classes-and-objects-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](#def-g12-classes-and-objects-pure-function) 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](#def-g12-classes-and-objects-class) of the chapter? How can it be made to show `(1, 2)`?

**Solution of Exercise 23.1.**

Something like `<__main__.Point object at 0x7f3a...>`: the [class](#def-g12-classes-and-objects-class) name and a memory address, which changes from run to run. Defining a [special method](#def-g12-classes-and-objects-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 of Exercise 23.2.**

$b = \frac12 + \frac14 = \frac34$ and $c = \frac34 \times \frac23 = \frac{6}{12} = \frac12$: `print(b, c)` shows `3/4 1/2`, and `print(repr(c))` shows `Fraction(1, 2)`.

**Exercise 23.3 ★.**

Write a [class](#def-g12-classes-and-objects-class) `Tally` with a [method](#def-g12-classes-and-objects-class) `add(k=1)`, which adds `k` to a count starting at $0$, and a [method](#def-g12-classes-and-objects-class) `value()`.

**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 of Exercise 23.4.**

`p` and `q` are one object, moved once: both are at $(3, 2)$. `r` is a new object built from those values, then moved: $(3, 3)$; moving it changed neither `p` nor `q`.

**Exercise 23.5 ★.**

A student writes `def move(dx, dy):` in the [class](#def-g12-classes-and-objects-class) `Point`. The call `p.move(1, 1)` raises `TypeError: Point.move() takes 2 positional arguments but 3 were given`. Explain the three.

**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](#def-g12-classes-and-objects-class) 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 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](#def-g12-classes-and-objects-constructor), which reduces it: the invariant is the [class](#def-g12-classes-and-objects-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](#def-g12-classes-and-objects-class) also defines `__hash__`?

**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](#def-g12-classes-and-objects-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](#def-g12-classes-and-objects-class) 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 of Exercise 23.8.**

`B in`, `A`, `B out`: `super().__init__()` runs the [constructor](#def-g12-classes-and-objects-constructor) of `A` in the middle of that of `B`. Without the call, `B in` and `B out` only: the [constructor](#def-g12-classes-and-objects-constructor) of `A` never runs, and any [attribute](#def-g12-classes-and-objects-class) it would have set is missing from the object.

**Exercise 23.9 ★★.**

Write a [method](#def-g12-classes-and-objects-class) `previous_day` for the [class](#def-g12-classes-and-objects-class) `Date`, and check it on 1 March 2028 and 1 January 2027.

**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](#def-g12-classes-and-objects-class) with the calendar of the [standard library](https://one-course.com/books/computer-science/2/en/chapter/20-modules-interfaces-and-libraries#def-g11-modules-and-interfaces-library) on $1200$ 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 $1$.

**Solution of Exercise 23.10.**

Every fraction is made by the [constructor](#def-g12-classes-and-objects-constructor), since `+` and `*` return `Fraction(...)`. So it is enough to check the [constructor](#def-g12-classes-and-objects-constructor), for any numerator $a$ and denominator $b \ne 0$. Let $g = \gcd(a, b)$, positive since $b \ne 0$. The divisions $a / g$ and $b / g$ are exact, and two numbers divided by their greatest common divisor have no common divisor other than $1$: a common divisor $d > 1$ of $a/g$ and $b/g$ would make $dg$ a common divisor of $a$ and $b$ larger than $g$. If $b < 0$, both are divided by $-g$ instead: the signs change, the common divisors do not, and the denominator $b / (-g)$ is positive. For `+` and `*`, the denominator passed is the product of two positive denominators, never $0$, so the [constructor](#def-g12-classes-and-objects-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 of Exercise 23.11.**

    `total = sum(map(lambda x: x * x, filter(lambda x: x % 2 == 0, t)))`

or, with a [comprehension](https://one-course.com/books/computer-science/2/en/chapter/2-tuples-sets-and-comprehensions#def-g10-tuples-sets-comprehensions-comprehension), `sum(x * x for x in t if x % 2 == 0)`. For `t = range(7)`: $0 + 4 + 16 + 36 = 56$.

**Exercise 23.12 ★★★.**

Write a [class](#def-g12-classes-and-objects-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 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 $1$ then $2$, `pop()` returns $2$, then `peek()` returns $1$ and `len` is $1$; 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 $k$ from $1$ to $4$, `total = total + Fraction(1, k)`. How many are still reachable at the end?

**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`, $25/12$; the eight others are no longer named by anything, and Python frees their memory.

**Exercise 23.14 ★★★.**

A [class](#def-g12-classes-and-objects-class) `Basket` has the line `items = []` in its body, outside any [method](#def-g12-classes-and-objects-class), and a [method](#def-g12-classes-and-objects-class) `add` that appends to `self.items`. After `a.add("pear")`, the basket `b` also holds a pear. Explain and correct.

**Solution of Exercise 23.14.**

`items = []` in the body of the [class](#def-g12-classes-and-objects-class) makes one list, an [attribute](#def-g12-classes-and-objects-class) of the [class](#def-g12-classes-and-objects-class) itself. `self.items` looks for an [attribute](#def-g12-classes-and-objects-class) of the object, finds none, and finds the [class](#def-g12-classes-and-objects-class)’s: every basket appends to the same list. The repair gives each object its own list in the [constructor](#def-g12-classes-and-objects-constructor):

    `def __init__(self):`

        `self.items = []`

**Exercise 23.15 ★★★.**

Write a [class](#def-g12-classes-and-objects-class) `Polynomial` built from its list of coefficients $[a_0, a_1, \dots]$, with `__add__`, `__mul__`, and `__call__` so that `p(x)` computes the value at `x`.

**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](#def-g12-classes-and-objects-constructor) drops the zero coefficients at the end, so that $(1 + x)^2 - x^2$ is stored as `[1, 2]`. The term $x^i$ times $x^j$ goes to $x^{i+j}$. `__call__` evaluates from the highest coefficient down, one multiplication per coefficient: $(1 + x)^2$ at $2$ gives $9$.

## 23.7 Problem: Exact Fractions

**Problem 23.1.**

Weekend problem — the harmonic sums, exactly

The harmonic sums are $H_n = 1 + \frac12 + \frac13 + \dots + \frac1n$. With the [class](#def-g12-classes-and-objects-class) `Fraction`, a program computes them exactly, compares their denominators with the least common multiple of $1, \dots, n$, and measures the error of the same sums in floating point.

```python
"""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())))
```

***Listing 23.11.** Harmonic sums exact and in floating point. code/grade-12/02-classes-and-objects/listings/harmonic.py*

```
$ 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
```

***Output 23.8.** The exact sums, their denominators, and three comparisons with floating point.*

**Part I — A class of fractions.**

1. Which [attributes](#def-g12-classes-and-objects-class) does a `Fraction` have, and why do their names start with an underscore?
2. What does `Fraction(10, -4)` store?
3. Which [special method](#def-g12-classes-and-objects-special-method) does `exact + Fraction(1, n)` call, and with which arguments?
4. Why does `Fraction(1, 2) == Fraction(2, 4)` hold, although $2/4$ was written?
5. Why does the [class](#def-g12-classes-and-objects-class) define `numerator()` and `denominator()` rather than letting users read `_num` and `_den` ?

**Part II — The invariant.**

6. State the invariant of `Fraction` .
7. Prove that the [constructor](#def-g12-classes-and-objects-constructor) establishes it, whatever the signs of its arguments (the denominator not $0$ ).
8. Show that `__eq__` is right because of the invariant: two fractions are equal numbers exactly when their reduced forms are equal.
9. What does `bad_mutation.py` show about Python’s protection of [attributes](#def-g12-classes-and-objects-class) ?

**Part III — The harmonic sums exactly.**

10. Compute $H_4$ by hand, and check the output.
11. From the output, give $H_9$ and $H_{10}$ . Check $H_{10} = H_9 + \frac{1}{10}$ .
12. How many digits has the numerator of $H_{1000}$ ? Why could no type of fixed size hold it?
13. Why can no [floating-point number](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float) hold $H_3 = 11/6$ exactly?

**Part IV — Denominators and floating point.**

14. Why is $\operatorname{lcm}(1, \dots, n)$ always a common denominator of the terms of $H_n$ ?
15. For which $n$ of the output is the reduced denominator smaller than that common multiple? By how much?
16. For $n = 6$ , write $H_6$ over $60$ and explain why it reduces by $3$ .
17. At $n = 10$ and $n = 100$ , how large is the floating-point error printed? And at $n = 1000$ ?
18. Where does that error come from? Recall chapter [4](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#ch-g10-floating-point) .
19. Why is the error at $n = 1000$ so small compared with the value?
20. State the result: $H_{10}$ exactly, and the error of the floating-point sum up to $1000$ .

**Solution of Problem 23.1.**

**1.** `_num` and `_den`. The underscore says they are internal: users go through the [methods](#def-g12-classes-and-objects-class), which keep the invariant.

**2.** $\gcd(10, -4) = 2$; the denominator is negative, so both are divided by $-2$: `_num` is $-5$ and `_den` is $2$.

**3.** `__add__`, with `self` the fraction named `exact` and `other` the new `Fraction(1, n)`.

**4.** The [constructor](#def-g12-classes-and-objects-constructor) stored $2/4$ as $1/2$; `__eq__` then compares $1$ with $1$ and $2$ with $2$.

**5.** The [methods](#def-g12-classes-and-objects-class) give read access only, so that no user can break the invariant by writing; and the [class](#def-g12-classes-and-objects-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 $1$.

**7.** Exercise [23.10](#exo-g12-classes-and-objects-10).

**8.** Let $a/b$ and $c/d$ be reduced, with $b, d > 0$. If they are equal numbers, $ad = bc$. Then $b$ divides $ad$ and has no common divisor with $a$, so $b$ divides $d$; in the same way $d$ divides $b$. Both being positive, $b = d$, and then $a = c$. Equal numbers have equal [attributes](#def-g12-classes-and-objects-class), so comparing [attributes](#def-g12-classes-and-objects-class) is right; without the invariant, $1/2$ and $2/4$ 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 $2/2$ is not $1$.

**10.** $\frac{12}{12} + \frac{6}{12} + \frac{4}{12} + \frac{3}{12} = \frac{25}{12}$, as printed.

**11.** $H_9 = 7129/2520$ and $H_{10} = 7381/2520$; $\frac{1}{10} = \frac{252}{2520}$, and $7129 + 252 = 7381$.

**12.** $434$ digits. A $64$-bit integer holds at most $2^{64} - 1$, which has $20$ digits; Python’s integers grow as needed (chapter [3](https://one-course.com/books/computer-science/2/en/chapter/3-integers-in-the-machine#ch-g10-machine-integers)).

**13.** A [floating-point number](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float) is a whole number of at most $53$ bits times a power of $2$ (chapter [4](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#ch-g10-floating-point)): its denominator is a power of $2$. $11/6$ has the factor $3$ in its reduced denominator, so its binary writing never ends, and every [floating-point number](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float) differs from it.

**14.** Each $k$ from $1$ to $n$ divides $\operatorname{lcm}(1, \dots, n)$, so $\frac1k$ is the fraction with that denominator and numerator $\operatorname{lcm}(1, \dots, n) / k$, a whole number.

**15.** For $n = 6$, $7$ and $8$, by a factor $3$; for $n = 20$, by a factor $15$. For the other printed values the reduced denominator is the common multiple itself.

**16.** $\operatorname{lcm}(1, \dots, 6) = 60$, and $H_6 = \frac{60 + 30 + 20 + 15 + 12 + 10}{60} =
\frac{147}{60}$. $147 = 3 \times 49$ and $60 = 3 \times 20$: $H_6 = 49/20$.

**17.** $0$ at $n = 10$ and $n = 100$: the floating-point sum is the closest [floating-point number](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float) to the exact value. At $n = 1000$, $-1.8 \times 10^{-15}$.

**18.** Each addition rounds its result to the nearest [floating-point number](https://one-course.com/books/computer-science/2/en/chapter/4-floating-point-numbers#def-g10-floating-point-float), and $1/k$ 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 $7.49$, so the error is about $2.4 \times 10^{-16}$ of it: two units of the last bit for numbers between $4$ and $8$, whose spacing is $2^{-50} \approx 8.9 \times 10^{-16}$. Fifteen significant digits are right.

**20.** **$H_{10} = 7381/2520$ exactly; summed in floating point up to $n = 1000$, the harmonic sum is off by $1.8 \times 10^{-15}$, about $2 \times 10^{-16}$ of its value $7.485\,470\,860\,550\,345$.**
