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.
Which line correctly defines a class TrialPatient that inherits from an existing Patient class?
A child class's __init__ needs to set the parent's attributes too. What is the recommended way?
TrialPatient defines a label method that overrides Patient.label. From inside TrialPatient.label, how do you call the parent's version?
TrialPatient inherits from Patient, which defines bmi(); TrialPatient does not define bmi() itself. What happens when you call tp.bmi() on a TrialPatient?
Why is super().__init__(...) preferred over copying the parent's self.x = x lines into the child?
Patient defines label(); TrialPatient overrides label() with its own version. For tp = TrialPatient(...), which version runs when you call tp.label()?
is_treatment() is defined only on the child TrialPatient, not on Patient. What happens if you call it on a plain Patient object?
Patient.label() returns the text Patient T001. A child overrides it as return "Trial " + super().label(). What does the child's label() return?
I can build a child class that inherits from a parent class, call super().__init__ correctly, and override one of the parent's methods.
2 Introduction
You wrote a Reading class for the potassium result of one patient in the last lesson. Now some readings come from a research study. They need two more facts. Copying the class would leave you with two almost identical classes to keep up to date.
This lesson covers how to build a new class on top of an existing one, how to let the existing class do the shared setup, and how to add new methods, replace methods or add to them.

Try every example in the Python Scratchpad on the right.
3 Inheritance and extending classes
The Reading class works. Then a new requirement arrives. A study reading holds everything a plain reading holds, and two more facts. These are a study code and the group the patient was put in.
Copying the class, renaming the copy StudyReading and adding the two new attributes is tempting. This works. But suppose the limit in is_high is later lowered from 5.5 to 5.0. You change only Reading.
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.0 # the limit was lowered from 5.5
class StudyReading:
def __init__(self, name, ward, potassium, study, group):
self.name = name
self.ward = ward
self.potassium = potassium
self.study = study
self.group = group
def is_high(self):
return self.potassium > 5.5 # the copy still has the old limit
print(Reading("Tan", "5A", 5.2).is_high()) # True
print(StudyReading("Tan", "5A", 5.2, "RENAL-2", "control").is_high()) # FalseThe same result, 5.2 mmol/L, is high for one class and not for the other. Python reports no error.
Inheritance is the way to say a new class is the same as an existing class, plus a few extras.

3.1 Terminologies
Three terms are used in this lesson.
- The parent class, also called the base class, is the class you start from. Here it is
Reading. - The child class, also called the subclass, is the new class built on the parent. Here it is
StudyReading. super()lets the child class call a method of the parent class.
3.2 Your first child class
The inheritance syntax is one line. You put the parent name in round brackets after the child name: class StudyReading(Reading):. The child class then has every method of the parent. You write only the extras.
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
class StudyReading(Reading):
def __init__(self, name, ward, potassium, study, group):
super().__init__(name, ward, potassium)
self.study = study
self.group = group
ng = StudyReading("Ng", "5A", 6.1, "RENAL-2", "control")
print(ng.study) # RENAL-2
print(ng.ward) # 5A
print(ng.is_high()) # TrueThe child needs its own __init__. This is because it takes two more values. Its first line calls super().__init__(name, ward, potassium). This gives the three shared values to the parent. The parent stores them on the object. The child then stores its own two values.
So the parent stored ng.ward. The child stored ng.study. The method is_high was never written in the child. But ng.is_high() still runs. Now type a similar example for a patient in a trial.
Try this snippet in the Python Scratchpad on the right.
class Patient:
def __init__(self, patient_id, age, weight_kg, height_m):
self.patient_id = patient_id
self.age = age
self.weight_kg = weight_kg
self.height_m = height_m
def bmi(self):
return self.weight_kg / (self.height_m ** 2)
class TrialPatient(Patient):
def __init__(self, patient_id, age, weight_kg, height_m, trial_id, cohort):
super().__init__(patient_id, age, weight_kg, height_m)
self.trial_id = trial_id
self.cohort = cohort
tp = TrialPatient("T001", 49, 80, 1.78, "TRIAL_A", "treatment")
print(tp.trial_id)
print(tp.bmi())

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())
3.3 Why super().__init__ is better
There are two ways to give the child the three shared values. Option A copies the parent's three lines into the child's __init__. Option B calls super().__init__(...), as in the last section. Both options work.
The difference shows up later. Suppose you decide that a ward must always be stored without the spaces around it. You change one line in the parent: self.ward = ward.strip(). The next example uses the same untidy ward for both options.
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward.strip()
self.potassium = potassium
class StudyReadingA(Reading):
def __init__(self, name, ward, potassium, study):
self.name = name
self.ward = ward
self.potassium = potassium
self.study = study
class StudyReadingB(Reading):
def __init__(self, name, ward, potassium, study):
super().__init__(name, ward, potassium)
self.study = study
a = StudyReadingA("Kumar", " 5A ", 5.8, "RENAL-2")
b = StudyReadingB("Kumar", " 5A ", 5.8, "RENAL-2")
print("[" + a.ward + "]") # [ 5A ]
print("[" + b.ward + "]") # [5A]Option A still has the old line, self.ward = ward. The parent now removes the spaces. The child of Option A does not. So a plain reading stores a tidy ward, but an Option A study reading stores an untidy one. Python reports no error. This is a bug.
Option B copied nothing. It asked the parent to do its own setup. So the child gets whatever the parent does now, and whatever you change in it later.

Type the code below into the Python Scratchpad and run it. It prints one line of text for each patient.
Try this snippet in the Python Scratchpad on the right.
class Patient:
def __init__(self, patient_id, weight_kg, height_m):
self.patient_id = patient_id
self.weight_kg = weight_kg
self.height_m = height_m
def label(self):
return f"Patient {self.patient_id}"
class TrialPatient(Patient):
def __init__(self, patient_id, weight_kg, height_m, trial_id):
super().__init__(patient_id, weight_kg, height_m)
self.trial_id = trial_id
def label(self):
return f"Trial patient {self.patient_id} ({self.trial_id})"
p = Patient("P001", 72, 1.75)
tp = TrialPatient("T001", 80, 1.78, "TRIAL_A")
print(p.label())
print(tp.label())
There is a shorter way to write the child's __init__ when the child only adds attributes. The child names only its own parameters. A parameter written as **kwargs collects every other keyword argument into a dictionary. So the caller passes the shared values by name.
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward
self.potassium = potassium
class StudyReading(Reading):
def __init__(self, study, group, **kwargs):
super().__init__(**kwargs)
self.study = study
self.group = group
ng = StudyReading(study="RENAL-2", group="control", name="Ng", ward="5A", potassium=6.1)
print(ng.name, ng.ward, ng.study) # Ng 5A RENAL-2Then super().__init__(**kwargs) opens the dictionary back up into separate arguments for the parent. The child's __init__ never mentions name, ward or potassium. So if the parent gains a new shared attribute later, this child needs no change. Now type the same pattern for a patient.
Try this snippet in the Python Scratchpad on the right.
class Patient:
def __init__(self, patient_id, age, weight_kg, height_m):
self.patient_id = patient_id
self.age = age
self.weight_kg = weight_kg
self.height_m = height_m
class TrialPatient(Patient):
def __init__(self, trial_id, **kwargs):
super().__init__(**kwargs)
self.trial_id = trial_id
tp = TrialPatient(trial_id="TRIAL_A", patient_id="T001", age=49, weight_kg=80, height_m=1.78)
print(tp.trial_id, tp.patient_id, tp.age)
3.4 Adding: Introducing new methods
A child class can have methods that the parent does not have. They are written like any other method, with self first.
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
class StudyReading(Reading):
def __init__(self, name, ward, potassium, study, group):
super().__init__(name, ward, potassium)
self.study = study
self.group = group
def is_control(self):
return self.group == "control"
def needs_review(self):
return self.is_high() and self.is_control()
ng = StudyReading("Ng", "5A", 6.1, "RENAL-2", "control")
print(ng.is_control()) # True
print(ng.needs_review()) # True
kumar = Reading("Kumar", "5A", 5.8)
print(kumar.is_control())
# AttributeError: 'Reading' object has no attribute 'is_control'Two things to notice:
is_controlreadsself.group, which exists only on a study reading. This is why the method is written in the child and not in the parent.needs_reviewcallsself.is_high(), a method written in the parent. A method from the parent is called throughselfexactly like a method written in the child.
The last line raises an AttributeError. This is because the class Reading has no method called is_control. A plain reading has no group. So the question does not apply to it.

3.5 Overriding: replacing a parent’s method
A child class can also replace a method of the parent. This is called overriding. The child defines a method with the same name as the parent's method. The child's version is then the one that runs.
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward
self.potassium = potassium
def report(self):
return f"{self.name}: {self.potassium} mmol/L"
class StudyReading(Reading):
def __init__(self, name, ward, potassium, study, group):
super().__init__(name, ward, potassium)
self.study = study
self.group = group
def report(self):
return f"{self.name} ({self.study}): {self.potassium} mmol/L"
kumar = Reading("Kumar", "5A", 5.8)
ng = StudyReading("Ng", "5A", 6.1, "RENAL-2", "control")
print(kumar.report()) # Kumar: 5.8 mmol/L
print(ng.report()) # Ng (RENAL-2): 6.1 mmol/LPython looks at the object first. For kumar, it finds report on the class Reading. For ng, it finds report on the class StudyReading. So it uses that one instead. The version in Reading is not deleted and not changed. The same call gives two different lines of text. This is because the objects were built from different classes.
Try this snippet in the Python Scratchpad on the right.
class Patient:
def __init__(self, patient_id):
self.patient_id = patient_id
def label(self):
return f"Patient {self.patient_id}"
class TrialPatient(Patient):
def __init__(self, patient_id, trial_id):
super().__init__(patient_id)
self.trial_id = trial_id
def label(self): # same name as parent's method, so this replaces it
return f"Trial patient {self.patient_id} ({self.trial_id})"
p = Patient("P001")
tp = TrialPatient("T001", "TRIAL_A")
print(p.label()) # Patient P001
print(tp.label()) # Trial patient T001 (TRIAL_A)

3.6 Extending: calling the parent’s method as part of yours
Sometimes you do not want to replace the parent's method. You only want to add to it. Inside the child's method, super().report() runs the parent's version and gives back its text.
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward
self.potassium = potassium
def report(self):
return f"{self.name}: {self.potassium} mmol/L"
class StudyReading(Reading):
def __init__(self, name, ward, potassium, study, group):
super().__init__(name, ward, potassium)
self.study = study
self.group = group
def report(self):
return super().report() + ", " + self.group + " group"
ng = StudyReading("Ng", "5A", 6.1, "RENAL-2", "control")
print(ng.report()) # Ng: 6.1 mmol/L, control groupThe child's report gives back the parent's line with the group added to the end. The first part of the line is still written in the parent. If the parent's report changes later, the child's text changes with it. This is because nothing was copied.
Try this snippet in the Python Scratchpad on the right.
class Patient:
def __init__(self, patient_id):
self.patient_id = patient_id
def label(self):
return f"Patient {self.patient_id}"
class TrialPatient(Patient):
def __init__(self, patient_id, trial_id):
super().__init__(patient_id)
self.trial_id = trial_id
def label(self):
return f"[{self.trial_id}] " + super().label() # prepend, then reuse parent's work
tp = TrialPatient("T001", "TRIAL_A")
print(tp.label()) # [TRIAL_A] Patient T001
Now put three readings in one list and call report on each one.
class Reading:
def __init__(self, name, ward, potassium):
self.name = name
self.ward = ward
self.potassium = potassium
def report(self):
return f"{self.name}: {self.potassium} mmol/L"
class StudyReading(Reading):
def __init__(self, name, ward, potassium, study, group):
super().__init__(name, ward, potassium)
self.study = study
self.group = group
def report(self):
return super().report() + ", " + self.group + " group"
kumar = Reading("Kumar", "5A", 5.8)
ng = StudyReading("Ng", "5A", 6.1, "RENAL-2", "control")
lim = StudyReading("Lim", "7B", 3.9, "RENAL-2", "treated")
for reading in [kumar, ng, lim]:
print(reading.report())
# Kumar: 5.8 mmol/L
# Ng: 6.1 mmol/L, control group
# Lim: 3.9 mmol/L, treated groupThe plain reading answers with the parent's version. The two study readings answer with their own. The loop has no if statement. Each object already knows which version of the method belongs to it.

4 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.
Which line correctly defines a class TrialPatient that inherits from an existing Patient class?
A child class's __init__ needs to set the parent's attributes too. What is the recommended way?
TrialPatient defines a label method that overrides Patient.label. From inside TrialPatient.label, how do you call the parent's version?
TrialPatient inherits from Patient, which defines bmi(); TrialPatient does not define bmi() itself. What happens when you call tp.bmi() on a TrialPatient?
Why is super().__init__(...) preferred over copying the parent's self.x = x lines into the child?
Patient defines label(); TrialPatient overrides label() with its own version. For tp = TrialPatient(...), which version runs when you call tp.label()?
is_treatment() is defined only on the child TrialPatient, not on Patient. What happens if you call it on a plain Patient object?
Patient.label() returns the text Patient T001. A child overrides it as return "Trial " + super().label(). What does the child's label() return?
I can build a child class that inherits from a parent class, call super().__init__ correctly, and override one of the parent's methods.
5 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?