Section 1

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.

Pre-test

Which line correctly defines a class TrialPatient that inherits from an existing Patient class?

Pre-test

A child class's __init__ needs to set the parent's attributes too. What is the recommended way?

Pre-test

TrialPatient defines a label method that overrides Patient.label. From inside TrialPatient.label, how do you call the parent's version?

Pre-test

TrialPatient inherits from Patient, which defines bmi(); TrialPatient does not define bmi() itself. What happens when you call tp.bmi() on a TrialPatient?

Pre-test

Why is super().__init__(...) preferred over copying the parent's self.x = x lines into the child?

Pre-test

Patient defines label(); TrialPatient overrides label() with its own version. For tp = TrialPatient(...), which version runs when you call tp.label()?

Pre-test

is_treatment() is defined only on the child TrialPatient, not on Patient. What happens if you call it on a plain Patient object?

Pre-test

Patient.label() returns the text Patient T001. A child overrides it as return "Trial " + super().label(). What does the child's label() return?

Pre-confidence

I can build a child class that inherits from a parent class, call super().__init__ correctly, and override one of the parent's methods.

Not at all confident
Fully confident
Section 2

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.

Inheritance lets one class reuse and build on the attributes and methods of another, instead of redefining them from scratch.
Inheritance lets one class reuse and build on the attributes and methods of another, instead of redefining them from scratch.

Try every example in the Python Scratchpad on the right.

Section 3

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())  # False

The 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.

Subclasses can add new methods or override existing ones.
Subclasses can add new methods or override existing ones.
Section 3.1

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.
Section 3.2

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())  # True

The 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 it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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())
A subclass automatically receives every method from its parent class and can then add its own, so you reuse the parent's code instead of rewriting it.
A subclass automatically receives every method from its parent class and can then add its own, so you reuse the parent's code instead of rewriting it.

Now arrange the lines below into a working class.

Parsons problem · Build a Gene 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.

Line bank
  • self.chromosome = chromosome
  • def __init__(symbol, chromosome):
  • g = Gene("APOE", 19)
  • class Gene:
  • def __init__(self, symbol, chromosome):
  • print(g.symbol)
  • self.symbol = symbol
  • g = Gene.new("APOE", 19)
  • symbol = symbol
Your solution
  • Drop lines here, in order.

Type the code below into the Python Scratchpad and run it.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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())
Section 3.3

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.

When the parent class is later updated, only the subclass that calls super().__init__() inherits the change. The subclass that copied the parent's setup keeps the old code and silently produces stale, buggy output.
When the parent class is later updated, only the subclass that calls super().__init__() inherits the change. The subclass that copied the parent's setup keeps the old code and silently produces stale, buggy output.

Type the code below into the Python Scratchpad and run it. It prints one line of text for each patient.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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-2

Then 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 it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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)
Section 3.4

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_control reads self.group, which exists only on a study reading. This is why the method is written in the child and not in the parent.
  • needs_review calls self.is_high(), a method written in the parent. A method from the parent is called through self exactly 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.

A subclass inherits the parent's methods and introduces a new method that the parent does not have.
A subclass inherits the parent's methods and introduces a new method that the parent does not have.
Section 3.5

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/L

Python 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 it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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)
A subclass redefines a parent method under the same name, so subclass instances run the new version while the parent class is unchanged.
A subclass redefines a parent method under the same name, so subclass instances run the new version while the parent class is unchanged.
Section 3.6

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 group

The 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 it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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 group

The 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.

A subclass redefines a parent method but calls super() to reuse the parent's behaviour, then appends its own.
A subclass redefines a parent method but calls super() to reuse the parent's behaviour, then appends its own.
Section 4

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.

Post-test

Which line correctly defines a class TrialPatient that inherits from an existing Patient class?

Post-test

A child class's __init__ needs to set the parent's attributes too. What is the recommended way?

Post-test

TrialPatient defines a label method that overrides Patient.label. From inside TrialPatient.label, how do you call the parent's version?

Post-test

TrialPatient inherits from Patient, which defines bmi(); TrialPatient does not define bmi() itself. What happens when you call tp.bmi() on a TrialPatient?

Post-test

Why is super().__init__(...) preferred over copying the parent's self.x = x lines into the child?

Post-test

Patient defines label(); TrialPatient overrides label() with its own version. For tp = TrialPatient(...), which version runs when you call tp.label()?

Post-test

is_treatment() is defined only on the child TrialPatient, not on Patient. What happens if you call it on a plain Patient object?

Post-test

Patient.label() returns the text Patient T001. A child overrides it as return "Trial " + super().label(). What does the child's label() return?

Post-confidence

I can build a child class that inherits from a parent class, call super().__init__ correctly, and override one of the parent's methods.

Not at all confident
Fully confident
Section 5

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.

Your score

Submit the post-test to see your results.

Muddiest point

What is the one thing from this module that is still unclear to you?

Rate this module

Overall, how would you rate this module?

How likely are you to recommend this module to a peer? (0 = not at all, 10 = extremely likely)