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

Inside a class, what is the role of the self parameter in a method?

Pre-test

For methods to be usable in a chain like obj.step1().step2(), what must each method do?

Pre-test

When does a class's __init__ method run?

Pre-test

After p1 = Patient("P001", 54), which word best describes p1?

Pre-test

An object p1 was built from a Patient class. How do you read its age attribute?

Pre-test

The method def bmi(self): takes no other parameters. How does it get the weight and height it needs?

Pre-test

A method changes the object but ends without return self. What happens when you run obj.add(3).add(5)?

Pre-test

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?

Pre-confidence

I can define a class with an __init__ method that stores attributes on the instance, and create new objects from that class.

Not at all confident
Fully confident
Pre-confidence

I can write a method that returns self so that several calls on the same object can be chained together in one expression.

Not at all confident
Fully confident
Section 2

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.

Section 3

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 False

Two 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"]))  # False

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

Classes bundle related variables and behaviours into one named object for consistency.
Classes bundle related variables and behaviours into one named object for consistency.
Section 3.1

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.
  • self is the object a method works on. Python passes it in automatically.
Important terminologies in object-oriented programming.
Important terminologies in object-oriented programming.

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.

__init__ stores all arguments into attributes.
__init__ stores all arguments into attributes.
Section 3.2

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
Different components that make up a class.
Different components that make up a class.

Look at three parts of this class:

  • The class name is written in PascalCase, with a capital letter starting each word.
  • __init__ takes self first, then the values you pass in. The parameter name disappears when __init__ ends. The value stored on the object stays.
  • is_high also takes self first. It needs no other parameter. This is because it reads the potassium result off the object, with self.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())  # True

Making 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 False

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

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 4

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.

Method chaining runs several operations on one object in a single line by passing it from one method to the next.
Method chaining runs several operations on one object in a single line by passing it from one method to the next.

You have already used method chaining on a string:

result = "  5.8 mmol/L ".strip().replace(" mmol/L", "")
print(result)  # 5.8

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

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

Method chaining works because each method returns the object it just modified via return self, so the next call has the same object to act on; without that return, the first method gives back None and the chain breaks at the very next call.
Method chaining works because each method returns the object it just modified via return self, so the next call has the same object to act on; without that return, the first method gives back None and the chain breaks at the very next call.

Type the code below into the Python Scratchpad and run it. It chains six method calls on one object.

Try it out

Try this snippet in the Python Scratchpad on the right.

Try this snippet
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 trim and drop_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.

Parsons problem · Chainable SymptomList

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.

Line bank
  • self.items = []
  • class SymptomList:
  • return self.items
  • s = SymptomList.add("Fever").add("Cough")
  • self.items.append(name.lower())
  • return self
  • return
  • def add(self, name):
  • def __init__(self):
  • print(s.items)
  • s = SymptomList().add("Fever").add("Cough")
Your solution
  • Drop lines here, in order.

Now build a chainable PatientRecord in the worked example.

Worked example · Building a chainable PatientRecord

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.

Stage 1 · Study the solved example
Fully solved solution
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)
Walk-through
  1. We define the class and initialise id and symptoms to empty values inside __init__.
  2. 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.
  3. We instantiate with PatientRecord() and immediately chain .set_id(...) and two .add_symptom(...) calls before the chain terminates and we read the attributes.
Section 5

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.

Post-test

Inside a class, what is the role of the self parameter in a method?

Post-test

For methods to be usable in a chain like obj.step1().step2(), what must each method do?

Post-test

When does a class's __init__ method run?

Post-test

After p1 = Patient("P001", 54), which word best describes p1?

Post-test

An object p1 was built from a Patient class. How do you read its age attribute?

Post-test

The method def bmi(self): takes no other parameters. How does it get the weight and height it needs?

Post-test

A method changes the object but ends without return self. What happens when you run obj.add(3).add(5)?

Post-test

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?

Post-confidence

I can define a class with an __init__ method that stores attributes on the instance, and create new objects from that class.

Not at all confident
Fully confident
Post-confidence

I can write a method that returns self so that several calls on the same object can be chained together in one expression.

Not at all confident
Fully confident
Section 6

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.

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)