1 Before you start
This is not graded, and it does not count towards anything. Answer every question even if you are only guessing — having a go at something before you have been taught it is one of the best ways to remember it afterwards. The lesson ends with another short check, and there you will be shown the correct answer for anything you missed. Choose an option for every question and confidence rating, then click Submit answers.
Inside a class, what is the role of the self parameter in a method?
For methods to be usable in a chain like obj.step1().step2(), what must each method do?
When does a class's __init__ method run?
After p1 = Patient("P001", 54), which word best describes p1?
An object p1 was built from a Patient class. How do you read its age attribute?
The method def bmi(self): takes no other parameters. How does it get the weight and height it needs?
A method changes the object but ends without return self. What happens when you run obj.add(3).add(5)?
Counter starts self.n at 0; its add(x) runs self.n = self.n + x then return self. What is Counter().add(3).add(5).add(2).n?
I can define a class with an __init__ method that stores attributes on the instance, and create new objects from that class.
I can write a method that returns self so that several calls on the same object can be chained together in one expression.
2 Introduction
Related data is often kept in separate variables. Every function that uses the data then needs all of them. A class keeps the data and the functions that use it under one name. You then build an object from the class. The object holds its own values and the functions that work on them.
This lesson covers how to write a class, build objects from it, and chain method calls on one object.
Try every example in the Python Scratchpad on the right.
3 Classes and why it matters
Suppose you track potassium results. Each patient has a name, a ward and a result in mmol/L. Each value gets its own variable. One function compares a result with a limit.
name_1 = "Kumar"
ward_1 = "5A"
potassium_1 = 5.8
name_2 = "Lim"
ward_2 = "7B"
potassium_2 = 3.9
def is_high(potassium, limit):
return potassium > limit
print(name_1, is_high(potassium_1, 5.5)) # Kumar True
print(name_2, is_high(potassium_2, 5.5)) # Lim FalseTwo patients need six variables. Ten patients would need thirty. A loop cannot go through them. This is because a variable name is not a list.
The usual fix is a dictionary for each patient. You put the dictionaries in a list, and a loop can go through the list.
def is_high(potassium, limit):
return potassium > limit
readings = [
{"name": "Kumar", "ward": "5A", "potassium": 5.8},
{"name": "Lim", "ward": "7B", "potassium": 3.9},
]
for r in readings:
print(r["name"], is_high(r["potassium"], 5.5)) # Kumar True, Lim False
print(is_high(5.5, readings[0]["potassium"])) # FalseThis works, but two things stay awkward:
- Every value needs square brackets and quote marks around its key.
- The function sits apart from the values. So you must remember which values to pass in, and in which order.
The example's last line passes the values in the wrong order. Python reports no error, but the answer False is wrong for Kumar. A class fixes both problems.

3.1 Terminologies
This lesson uses six terms:
- A class is a blueprint that describes the values a thing holds and what it can do.
- An object, also called an instance, is one specific thing built from the blueprint.
- An attribute is a value stored on an object.
- A method is a function that belongs to a class and works on the object. You reach an attribute or a method with a dot.
__init__sets up a new object. Its name has two underscores on each side.selfis the object a method works on. Python passes it in automatically.

Python runs __init__ each time you make an object. It stores on self the values that you pass in. So every other method can use them. __init__ is often called the constructor.

3.2 Defining classes and creating instances
This class holds one potassium result.
class Reading:
def __init__(self, name, ward, potassium):
self.name = name # store the name on this object
self.ward = ward # store the ward on this object
self.potassium = potassium # store the result on this object
def is_high(self):
return self.potassium > 5.5
Look at three parts of this class:
- The class name is written in PascalCase, with a capital letter starting each word.
__init__takesselffirst, then the values you pass in. The parameternamedisappears when__init__ends. The value stored on the object stays.is_highalso takesselffirst. It needs no other parameter. This is because it reads the potassium result off the object, withself.potassium.
Now make an object from the class. The values go to __init__ in parameter order:
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward
self.potassium = potassium
def is_high(self):
return self.potassium > 5.5
kumar = Reading("Kumar", "5A", 5.8)
print(kumar.ward) # 5A
print(kumar.is_high()) # TrueMaking kumar does three things. Python makes a new empty object. Python passes it in as self and runs __init__. The three values are stored on the object as attributes.
To read an attribute, write the object, a dot and the attribute name, with no square brackets or quote marks. To call a method, write the object, a dot, the method name and round brackets. Here the brackets stay empty. This is because Python passes the object in as self.
A second object has the same attribute names and methods, but holds its own values:
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward
self.potassium = potassium
def is_high(self):
return self.potassium > 5.5
kumar = Reading("Kumar", "5A", 5.8)
lim = Reading("Lim", "7B", 3.9)
readings = [kumar, lim]
for reading in readings:
print(reading.name, reading.ward, reading.is_high()) # Kumar 5A True, Lim 7B FalseThe same method gives two different answers. This is because self is a different object on each call. The loop goes through a list of both objects.
Now arrange the lines below into a working class.
All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.
Task: Build a class Gene that stores a gene symbol and a chromosome number, then create one and print its symbol.
self.chromosome = chromosomedef __init__(symbol, chromosome):g = Gene("APOE", 19)class Gene:def __init__(self, symbol, chromosome):print(g.symbol)self.symbol = symbolg = Gene.new("APOE", 19)symbol = symbol
- Drop lines here, in order.
Type the code below into the Python Scratchpad and run it.
Try this snippet in the Python Scratchpad on the right.
class BloodPressure:
def __init__(self, systolic, diastolic):
self.systolic = systolic
self.diastolic = diastolic
def category(self):
if self.systolic >= 140 or self.diastolic >= 90:
return "hypertensive"
if self.systolic >= 130 or self.diastolic >= 80:
return "elevated"
return "normal"
readings = [BloodPressure(118, 76), BloodPressure(134, 82), BloodPressure(152, 94)]
for bp in readings:
print(bp.systolic, bp.diastolic, bp.category())
4 Method chaining
Method chaining puts several method calls on the same object in one line. Each method hands the object back so the next method can work on it.
For example, a single line can standardise units, strip whitespace, fill missing values and flag quality issues on a sample.

You have already used method chaining on a string:
result = " 5.8 mmol/L ".strip().replace(" mmol/L", "")
print(result) # 5.8The strip() method removes spaces from the ends and gives back a new string. The replace() method then runs on that new string and removes the unit. Each dot has a string to work on. This is because strip() and replace() both give back a string.
You can write your own class that behaves this way. Each method must hand the same object back with the line return self.
class Field:
def __init__(self, text):
self.text = text
def trim(self):
self.text = self.text.strip()
return self
def drop_unit(self):
self.text = self.text.replace(" mmol/L", "")
return self
result = Field(" 5.8 mmol/L ").trim().drop_unit()
print(result.text) # 5.8The method trim() hands the object back so drop_unit() runs on the same object.
Now see what happens without return self. A method that ends without a return line gives back None. Here trim() has no return self:
class Field:
def __init__(self, text):
self.text = text
def trim(self):
self.text = self.text.strip()
def drop_unit(self):
self.text = self.text.replace(" mmol/L", "")
return self
result = Field(" 5.8 mmol/L ").trim().drop_unit()
# AttributeError: 'NoneType' object has no attribute 'drop_unit'None has no method called drop_unit. So the next dot raises an AttributeError. The first step already changed the object. But the line could not go on.

Type the code below into the Python Scratchpad and run it. It chains six method calls on one object.
Try this snippet in the Python Scratchpad on the right.
class SymptomList:
def __init__(self):
self.items = []
def add(self, name):
self.items.append(name)
return self
def strip_spaces(self):
self.items = [s.strip() for s in self.items]
return self
def lowercase(self):
self.items = [s.lower() for s in self.items]
return self
def dedupe(self):
self.items = list(dict.fromkeys(self.items))
return self
s = SymptomList().add(" Fever ").add("Cough").add("FEVER").strip_spaces().lowercase().dedupe()
print(s.items)
There are two rules of thumb for chainable methods:
- If a method changes the object, end it with
return self. - Each step should read as a verb acting on the same object, such as
trimanddrop_unit.
A single step is clearer on its own line. Chaining is useful when several steps belong to one larger job.
Now arrange the lines below into a chainable class.
All the lines you need are in the Line bank on the left — some may be distractors you should leave behind. Drag the lines you need into the Your solution column on the right, in the correct order, then click Check.
Task: Assemble a class whose .add() method returns self so the calls can be chained. Each .add() should lowercase the symptom before appending.
self.items = []class SymptomList:return self.itemss = SymptomList.add("Fever").add("Cough")self.items.append(name.lower())return selfreturndef add(self, name):def __init__(self):print(s.items)s = SymptomList().add("Fever").add("Cough")
- Drop lines here, in order.
Now build a chainable PatientRecord in the worked example.
Work through this example in three stages. You unlock each stage only after the tutor confirms the previous one. Each stage removes more of the scaffolding — by the end you are writing it yourself.
Problem: Write a PatientRecord class with two chainable methods, .set_id(id_str) and .add_symptom(name). Build a record for patient "P001" with symptoms fever and cough, then print the id and symptoms.
class PatientRecord:
def __init__(self):
self.id = None
self.symptoms = []
def set_id(self, id_str):
self.id = id_str
return self
def add_symptom(self, name):
self.symptoms.append(name)
return self
p = PatientRecord().set_id("P001").add_symptom("fever").add_symptom("cough")
print(p.id, p.symptoms)
- We define the class and initialise id and symptoms to empty values inside __init__.
- Each chainable method updates the attribute it owns and ends with return self — that is the line that hands the same object back to the next dot in the chain.
- We instantiate with PatientRecord() and immediately chain .set_id(...) and two .add_symptom(...) calls before the chain terminates and we read the attributes.
The same solution with key parts replaced by ???.
Fill in every ??? so the code matches the reference,
then ask the tutor to check it.
Your turn: Write a chainable DrugRegimen class with two methods: .set_patient(pid) and .add_drug(name). Build a regimen for patient "P042" with drugs "metformin" and "lisinopril". Print the patient id followed by the drug list.
5 Check your understanding
You have reached the end of the module. Try the same questions again — your answers here, paired with your pre-test answers, are how we measure what the module taught you. Answer every question and confidence rating, then click Submit and see results to view your score.
Inside a class, what is the role of the self parameter in a method?
For methods to be usable in a chain like obj.step1().step2(), what must each method do?
When does a class's __init__ method run?
After p1 = Patient("P001", 54), which word best describes p1?
An object p1 was built from a Patient class. How do you read its age attribute?
The method def bmi(self): takes no other parameters. How does it get the weight and height it needs?
A method changes the object but ends without return self. What happens when you run obj.add(3).add(5)?
Counter starts self.n at 0; its add(x) runs self.n = self.n + x then return self. What is Counter().add(3).add(5).add(2).n?
I can define a class with an __init__ method that stores attributes on the instance, and create new objects from that class.
I can write a method that returns self so that several calls on the same object can be chained together in one expression.
6 Your results
Here is how your post-test answers compare with your pre-test answers. The pre/post pairing is the most reliable way to see what this module actually taught you.
Submit the post-test to see your results.
What is the one thing from this module that is still unclear to you?