Bundling data with the code that works on it
October 16, 2026
Since Lecture 3 (strings) and Lecture 7 (dates) you have been writing things like these:
GRAMMAR
2026 Friday
<class 'str'> <class 'datetime.date'>
type has been answering <class ...> all along. Lecture 3 promised “which values offer which methods, and why, is Lecture 8”. Today:
Today’s notional machine gains one piece: the object, a box that holds boxes of its own. A value’s class decides which boxes it has and what it can do.
Every value in Python is an object. An object carries:
day.year;day.strftime("%A"). They are stored in the object’s class.Both are reached with a dot, so a missing one is an AttributeError either way (Lecture 3’s number.upper()).
2026 10 16
4
<built-in method strftime of datetime.date object at 0x1096dcab0>
The class is the kind of thing — date, str, list. An object is one particular value of that kind: date(2026, 10, 16) is an object of class date. Also called an instance of the class.
An experiment: each participant has a code, an age, and reaction times. With what we know, a dictionary, and functions next to it:
516.6666666666666
It works — until someone writes {"code": "sub-02", "age": 31, "rt": [...]}.
Nothing says what a participant must contain, and nothing ties mean_rt to participants. A class puts the two together: one place that says what a participant is and what you can ask it.
class and __init__sub-01 24 []
sub-02 31
<class '__main__.Participant'>
class Participant: — a new kind of value. Class names start with a capital letter, by convention.__init__ — the function that sets up each new object. You never call it: Python does, on Participant(...). The double underscores mark it as one of Python’s own names — more on those after __str__.self — this very object, the one being set up. self.code = code puts a box called code inside it. Two slides on, we watch it happen.Participant(...)Participant("sub-01", 24) looks like a function call, and it is three steps:
Participant;__init__ with self = that new object, code = "sub-01", age = 24;__init__ itself returns nothing.An object is a box of boxes — like the module of Lecture 7. p1.age means “go to the object in p1, open its box age”. Each object has its own.
self is the new objectStep 2 says self = that new object. Let us check: __init__ prints its self, and after the call we print what landed in p1 and p2.
inside __init__, self is <__main__.Participant object at 0x1090aa9f0>
after the call, p1 is <__main__.Participant object at 0x1090aa9f0>
inside __init__, self is <__main__.Participant object at 0x1096da540>
after the call, p2 is <__main__.Participant object at 0x1096da540>
Same address, same object. self is not a copy of the object: it is the object, under a temporary name. When __init__ ends, the name self goes — a local, Lecture 5 — and the object stays, now called p1. A second call makes a new object, and self is that one.
selfAnd without self? The two mistakes everybody makes once. Predict both:
TypeError: Participant.__init__() takes 2 positional arguments but 3 were given
Python always passes the new object first, so it counts 3 arguments — the object, the code, the age — and __init__ has places for 2.
AttributeError: 'Participant' object has no attribute 'code'
code = code makes a local box of __init__ (Lecture 5), gone when the call ends. The object comes out empty, and the error shows up only later, at p1.code.
self in the brackets receives the object; self. before a name puts the box inside it.
A function written inside the class is a method. Its first parameter is always self: the object it was called on.
class Participant:
def __init__(self, code, age):
self.code = code
self.age = age
self.rts = []
def add_rt(self, rt):
self.rts.append(rt)
def mean_rt(self):
total = 0
for rt in self.rts:
total += rt
return total / len(self.rts)
p1 = Participant("sub-01", 24)
p1.add_rt(512)
p1.add_rt(498)
print(p1.rts, p1.mean_rt())[512, 498] 505.0
self come from?You call p1.add_rt(540) with one argument, but the method has two parameters.
The object before the dot fills the first. Predict: does the second line work, and what is in p1.rts and p2.rts at the end?
[512, 498, 540, 600]
[300]
p1.add_rt(540) is shorthand for Participant.add_rt(p1, 540): find the function in the object’s class, and pass the object itself as self. That is how one method, written once, works on every participant.
<__main__.Participant object at 0x10971caa0>
Python does not know how you want a participant to look. Tell it, with another method with a double-underscore name, __str__:
sub-01 (age 24, trials: 0)
__init__ and __str__ are called by Python itself: the first by Participant(...), the second by print and by f-strings.
Names like __init__ and __str__ — dunder names, “double under” — are never called by you. You write ordinary Python, and the machine translates it into a call of a dunder method of the value’s class:
| You write | Python calls |
|---|---|
Participant("sub-01", 24) |
__init__, on the new object |
print(p1), f"{p1}" |
p1.__str__() |
len(word) |
word.__len__() |
a + b |
a.__add__(b) |
a == b |
a.__eq__(b) |
3 3
23 23
5 5
That is why the value decides what + does (Lecture 2): + asks the left value’s class for its __add__, and str and int each have their own. A dunder method is a hook: define it in your class, and the ordinary syntax starts working on your objects.
Objects go in lists like any other value — and everything from Lecture 4 works on them:
sub-01 (age 24, trials: 0)
sub-03 (age 19, trials: 0)
oldest: sub-02
The reference trap of Lecture 3, with objects. Predict:
42 42 True
42 42 True. One object, two names. Changing an attribute changes the object, so every name that leads to it sees the change — and so does the caller of a function that receives it (Lecture 5).
Everything so far in one place — the Participant that the inheritance slides build on:
class Participant:
def __init__(self, code, age):
self.code = code
self.age = age
self.rts = []
def add_rt(self, rt):
self.rts.append(rt)
def mean_rt(self):
total = 0
for rt in self.rts:
total += rt
return total / len(self.rts)
def __str__(self):
return f"{self.code} (age {self.age}, trials: {len(self.rts)})"
p1 = Participant("sub-01", 24)
p1.add_rt(512)
p1.add_rt(498)
print(p1, p1.mean_rt())sub-01 (age 24, trials: 2) 505.0
Some participants are patients: everything a participant has, plus a diagnosis. Do not copy the class — inherit from it:
class Patient(Participant): # a Patient IS a Participant
def __init__(self, code, age, diagnosis):
super().__init__(code, age) # let Participant set up its part
self.diagnosis = diagnosis
pt = Patient("sub-05", 67, "aphasia")
pt.rts.append(830)
print(pt) # __str__ comes from Participant
print(pt.diagnosis)
print(isinstance(pt, Participant), isinstance(p1, Patient))sub-05 (age 67, trials: 1)
aphasia
True False
Participant is the parent (or base) class, Patient the child.super().__init__(...) runs the parent’s __init__ on this object, so the setup is written once.pt.somethingThe search, in order — first match wins:
diagnosis, code, age, rts);Patient (__init__);Participant (__str__, add_rt, …);object, the ancestor of every class (where the default print and == come from);AttributeError.[830, 790]
AttributeError: 'Patient' object has no attribute 'diagnosys'
The third lookup rule of the course, and the same shape as the other two: names in scopes (Lecture 2), modules on the search path (Lecture 7), and now attributes along the classes. An ordered search, first match wins.
A child can replace a method of its parent by defining one with the same name. Predict the two lines — does the new __str__ change the participant too?
class Patient(Participant):
def __init__(self, code, age, diagnosis):
super().__init__(code, age)
self.diagnosis = diagnosis
def __str__(self):
basic = super().__str__() # the parent's version...
return f"{basic}, {self.diagnosis}" # ...plus one more piece
print(Patient("sub-05", 67, "aphasia"))
print(Participant("sub-06", 22))sub-05 (age 67, trials: 0), aphasia
sub-06 (age 22, trials: 0)
The search starts from the object: a patient finds Patient.__str__ before it ever reaches the parent’s. A participant starts its search in Participant and never looks at Patient. Overriding changes the child only.
You have met this since Lecture 2: the value decides what an operation does.
3 4 1
5 23
Your classes can join in: different classes, same method name, each with its own answer. One loop, one print(p) — predict the two lines:
sub-01 (age 24, trials: 0)
sub-05 (age 67, trials: 0), aphasia
Polymorphism: many shapes. The loop asks every object the same thing, and each one answers in its own way. Adding a new kind of participant needs no change to the loop.
A new version of Participant, with rts renamed _rts. Its add_rt refuses impossible values: under 100 ms is too fast for a real response, so it counts as an anticipation. MIN_RT is a class attribute, one box in the class (step 2 of the lookup):
class Participant:
MIN_RT = 100 # one value shared by the whole class
def __init__(self, code, age):
self.code = code
self.age = age
self._rts = [] # _ : "internal, use the methods"
def add_rt(self, rt):
if rt < Participant.MIN_RT:
return False # refused
self._rts.append(rt)
return True
def n_trials(self):
return len(self._rts)
p = Participant("sub-01", 24)
print(p.add_rt(512), p.add_rt(87), p.n_trials())True False 1
The underscore in _rts is a message to other programmers: “do not touch this from outside — use the methods”. Python does not enforce it:
2 [512, 5]
Encapsulation means the class decides how its data may change: through its methods, which check. A leading _ marks what is internal. Respect it in other people’s classes, and use it in yours.
MIN_RT lives in the class, shared by every participant. So why not the list of trials too? Each session should start with none — predict the last line:
[512] [512] True
trials is a class attribute: one box, in the class. Neither object has a trials of its own, so the lookup finds the class’s at step 2, for both — and append changes that one shared list. Fix: self.trials = [] inside __init__, one new list per object. Constants in the class; anything you fill or change, in __init__.
Book class, in a moduleThe read_book of Lecture 6, packed into an object that remembers its lines and can give you its words. A class lives in a module like a function does (Lecture 7), so it goes in texts.py:
# texts.py
"""Gutenberg books as objects."""
class Book:
"""A Gutenberg book: its lines, without the licence."""
def __init__(self, path):
self.lines = []
inside = False
with open(path, "r", encoding="utf-8") as f:
for line in f:
if line.startswith("*** END OF"):
break
if inside:
self.lines.append(line.strip())
if line.startswith("*** START OF"):
inside = True
def words(self):
"""Return every word, lower-cased, without outer punctuation."""
result = []
for line in self.lines:
for w in line.split():
w = w.lower().strip(".,;:!?()\"'“”‘’-—")
if w != "":
result.append(w)
return resultBookIn main.py, in the same folder:
(intro2python) $ python main.py
8 lines, 62 words
[('the', 4), ('of', 3), ('or', 3)]
main.py reads like the task: open the book, count its words, give me the top three. How the licence is skipped or the punctuation removed lives in one place, inside the class — and the class in one file, texts.py.
__init__(self, ...) sets up each new object; self is that object, and self.x = ... stores on it. Dunder methods (__init__, __str__, __len__, …) are called by Python for you.obj.method(a) is Class.method(obj, a): the object becomes self.class Child(Parent):, super().__init__(...); lookup goes object → class → parent._internal, change data through methods.__init__. Classes live in modules, like functions.Predict the four lines:
2 1 2
True False
True
False
2 1 2 — c = a made a second name for the same object, so changing c.value changed a’s too; b is a different object.
True False — is asks “the same object?” (Lecture 3).
True — the two values are both 2.
False — Box(1) builds a new object, and for our own classes == means “the same object” unless the class says otherwise.
Each line uses the Participant class with add_rt and n_trials. Name what happens — error or not. One click per answer.
<bound method Participant.n_trials of <__main__.Participant object at 0x1096dbb00>>
TypeError: Participant.__init__() missing 1 required positional argument: 'age'
No error, but no call: without brackets you get the method itself · AttributeError: no such box, on the object or in its class · TypeError: __init__ needs code and age.
__str__, which sound?Predict the three lines:
class Animal:
def __init__(self, name):
self.name = name
def sound(self):
return "..."
def __str__(self):
return f"{self.name} says {self.sound()}"
class Dog(Animal):
def sound(self):
return "woof"
class Puppy(Dog):
def __str__(self):
return "a small " + super().__str__()
for a in [Animal("Rex"), Dog("Fido"), Puppy("Bea")]:
print(a)Rex says ...
Fido says woof
a small Bea says woof
__str__, which sound? — answerRex says ... — everything is found in Animal.
Fido says woof — __str__ is found in Animal, the parent. Inside it, self is still Fido, so self.sound() starts the search from the object again: Dog has a sound, and wins.
a small Bea says woof — __str__ is found in Puppy; super().__str__() runs Animal’s, and sound is found in Dog, Puppy’s parent.
print or return, againLecture 5’s question, inside a class. What appears on the screen?
Word: cat
TypeError: __str__ returned non-string (type NoneType)
Word: cat and a TypeError. print(w) calls __str__, which prints the line itself — then returns nothing, None, where print needed a string. __str__ must return the text.
Write a class Rectangle:
__init__(self, length, width) stores the two sides;area() returns the area, perimeter() the perimeter;__str__ returns something like "Rectangle 5 x 3".class Rectangle:
def __init__(self, length, width):
self.length = length
self.width = width
def area(self):
return self.length * self.width
def perimeter(self):
return 2 * self.length + 2 * self.width
def __str__(self):
return f"Rectangle {self.length} x {self.width}"
r = Rectangle(5, 3)
print(r, r.area(), r.perimeter())Rectangle 5 x 3 15 16
The methods read the sides from self, so the same area works for every rectangle you build.
Write a class Square that inherits from your Rectangle and takes a single side. It must reuse area() and perimeter() without rewriting them, and print as "Square 5".
Square 5 25 20
True
super().__init__(side, side) lets Rectangle store length and width; area and perimeter are then found in Rectangle by the lookup. Only __str__ is overridden.
Write a class Person with name, country and born (a date). Add a method age_on(on) that returns the person’s age in whole years on the day on, also a date.
Careful: subtracting the years is not enough.
from datetime import date
class Person:
def __init__(self, name, country, born):
self.name = name
self.country = country
self.born = born
def age_on(self, on):
age = on.year - self.born.year
before_month = on.month < self.born.month
same_month_before_day = on.month == self.born.month and on.day < self.born.day
if before_month or same_month_before_day:
age = age - 1 # birthday not reached yet
return age
ada = Person("Ada", "UK", date(2000, 12, 10))
print(ada.age_on(date(2026, 10, 16)), ada.age_on(date(2026, 12, 10)))
print(ada.age_on(date.today()))25 26
25
Passing the day in, instead of always using date.today(), makes the method testable: the first two calls give the same answer every year.
Write a class Account that keeps its money in _balance, starting at 0:
deposit(amount) adds; it refuses amounts that are not positive;withdraw(amount) subtracts; it refuses amounts that are not positive, or larger than the balance;True if they did it, False if they refused;balance() returns the current balance.class Account:
def __init__(self):
self._balance = 0
def deposit(self, amount):
if amount <= 0:
return False
self._balance = self._balance + amount
return True
def withdraw(self, amount):
if amount <= 0 or amount > self._balance:
return False
self._balance = self._balance - amount
return True
def balance(self):
return self._balance
acc = Account()
print(acc.deposit(100), acc.withdraw(30), acc.withdraw(500))
print(acc.deposit(-5))
print(acc.balance())True True False
False
70
Every change of _balance goes through a method that checks it first, and True / False tells the caller whether it happened.
Write corpus.py, next to the texts.py of the slides, with a class Corpus that uses Book:
__init__(self) starts with no books;add(path) reads a book and keeps it;n_words() returns the total number of words in all the books;most_common(n) — the n most common words over all the books.Test it from main.py by adding resources/mini_alice.txt twice: the counts must double.
# corpus.py
"""Several books, counted together."""
from collections import Counter
from texts import Book
class Corpus:
"""A collection of Book objects."""
def __init__(self):
self.books = []
def add(self, path):
"""Read the book at path and keep it."""
self.books.append(Book(path))
def all_words(self):
"""Return the words of every book, in one list."""
words = []
for book in self.books:
words = words + book.words()
return words
def n_words(self):
return len(self.all_words())
def most_common(self, n):
return Counter(self.all_words()).most_common(n)A Corpus holds Book objects and asks them for their words: it never opens a file itself. all_words is a helper the other two methods share.
(intro2python) $ python main.py
62 [('the', 4), ('of', 3)]
124 [('the', 8), ('of', 6)]
Three files, one job each: texts.py knows books, corpus.py knows collections of books, main.py knows the task.
resources/trials.json holds the trials of a lexical decision task: a word or a pseudo-word on screen, a key press, a reaction time.
[
{
"word": "table",
"condition": "real",
"rt": 512,
"correct": true
},
...
]
In trials.py:
Trial with word, condition, rt, correct, and a method is_valid(): correct and rt of at least 100 ms;load_trials(path) that returns a list of Trial objects from the file.In main.py: print, for real and for pseudo, the mean rt of the valid trials.
# trials.py
"""The trials of a lexical decision task."""
import json
class Trial:
"""One trial: the word shown, its condition, the response."""
def __init__(self, word, condition, rt, correct):
self.word = word
self.condition = condition
self.rt = rt
self.correct = correct
def is_valid(self):
"""True if answered correctly, and not an anticipation."""
return self.correct and self.rt >= 100
def load_trials(path):
"""Return the trials in the JSON file at path, as Trial objects."""
with open(path, "r", encoding="utf-8") as f:
rows = json.load(f)
trials = []
for row in rows:
trials.append(Trial(row["word"], row["condition"], row["rt"], row["correct"]))
return trialsload_trials turns each dictionary from the file into an object: from here on, the rest of the program never touches the raw dictionaries.
(intro2python) $ python main.py
real 505.0 ms over 2 trials
pseudo 682.0 ms over 3 trials
t.is_valid() keeps the rule in one place: change the 100 ms in trials.py and every program that uses it follows.
Intro to Programming (Python) · Fall 2026