Easier to read with cream paper, a tint, more contrast or larger text? Choose your colours and text, once, for every page.

Free lesson

Classes and objects in Python

After this lesson: I can model a thing as a class with state and behaviour.

50 min lesson6 commandsEveryday Linux commands lab: the thirty commands engineers type from memory

A class is a blueprint for objects

A class in Python is a blueprint that bundles data with the functions that work on that data. An object is one thing built from the blueprint. Classes let your code match the problem: a log line, a basket, a user. This is the start of object-oriented programming, and every pattern later in this module builds on it.

By the end of this lesson

Note

I can model a thing as a class with state and behaviour.

Key words

WordWhat it meansExample
Classa blueprint for making objects
Objectone thing made from a class
Attributea value stored inside an objectself.level
Methoda function that belongs to a classis_error
Constructorthe method that sets up a new object__init__
Statewhat an object's attributes hold right now

The cells students fill in are left blank in this preview.

One class, many objects

The lab keeps a log at /var/log/test.log. Each line has a date, a time, a level such as INFO or ERROR, and a message. A log line has data and things you do with it, so it makes a good class.

The class describes every log line. Each object is one real line. You write the class once and make as many objects as you need.

Read the level of a real error line

Command
grep -m 1 ERROR /var/log/test.log | cut -d" " -f3

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A LogLine class in Python

Code: python
class LogLine:
    def __init__(self, level, message):
        self.level = level
        self.message = message
        self.read = False

    def is_error(self):
        return self.level == "ERROR"

    def short(self):
        return self.level + ": " + self.message

    def mark_read(self):
        self.read = True

The constructor sets up each new object

The Run printed ERROR: the third word of that line is its level. The class above keeps level and message as attributes.

__init__ is the constructor. Python calls it when you write LogLine("ERROR", "disk full"). self is the object being built, so self.level = level stores the value inside that object. Every method takes self first, which is how it reaches that object's attributes.

Make a folder for this lesson

Command
mkdir -p ~/oop1

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Go into it

Command
cd ~/oop1

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Write the class to a file

Command
printf 'class LogLine:\n    def __init__(self, level, message):\n        self.level = level\n        self.message = message\n        self.read = False\n\n    def is_error(self):\n        return self.level == "ERROR"\n\n    def short(self):\n        return self.level + ": " + self.message\n\n    def mark_read(self):\n        self.read = True\n' > loglines.py

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Make two objects and call their methods

Command
python3 -c "from loglines import LogLine; a = LogLine('ERROR', 'disk full'); b = LogLine('INFO', 'started'); print(a.short()); print(b.short()); print(a.is_error(), b.is_error())"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

Each object keeps its own state

State is what an object's attributes hold now. A method can change it. mark_read sets self.read to True for that one object only.

Two objects from one class share the same methods and keep separate attributes. Changing one never changes the other.

Worked example: two objects, one change

Momenta.readb.read
Both just madeFalseFalse
After a.mark_read()TrueFalse
After b.mark_read()TrueTrue

The cells students fill in are left blank in this preview.

Change one object and check the other

Command
python3 -c "from loglines import LogLine; a = LogLine('INFO', 'started'); b = LogLine('INFO', 'started'); a.mark_read(); print(a.read, b.read)"

Shown here, not run. Create a free account to press Run and type it into your own lab’s terminal.

A common mistake

Warning

Many people think the class and the object are the same thing. The class is the blueprint and holds no log line itself. Write LogLine(...) to make an object, then call methods on that object, never on the class.

About this lab and its source: Everyday Linux commands lab: the thirty commands engineers type from memory

Teaching a class? Set this module for your students with a teacher guide, marked assignments and a lab for every student.