Skip to lesson content
navan✳THE BUILD LABPYTHON 3
0/101 complete
EXPERIMENT 22 / 101

Blueprints for behaviour.

Keep state and the operations that belong to it in one place.

BY NAVAN SAMI◷ 6 MIN READPYTHON 3

01 The idea

A class defines a kind of object. An instance has its own state, and methods describe behaviour that uses that state. __init__ initialises a newly created instance. The conventional name self refers to the instance inside a method.

02 The experiment

Read it once. Predict what will happen. Then copy it into a .py file and run it in your local Python setup.

classes.py
class Mission:
    def __init__(self, name):
        self.name = name
        self.completed = False

    def finish(self):
        self.completed = True

mission = Mission("Orbit")
mission.finish()
print(mission.name, mission.completed)
↳ EXPECTED OUTPUT
Orbit True

03 Under the hood

  1. 1

    Calling Mission("Orbit") creates an instance, then __init__ sets its initial attributes.

  2. 2

    finish() changes that instance’s completed attribute. A different Mission instance would have independent attributes assigned in its own __init__.

  3. 3

    Use classes when state and behaviour naturally belong together. A simple function or dictionary is often a better starting point for simpler data; a class is a tool, not a requirement.

04 Your turn, builder

A SMALL MISSION

Create a Counter class with value starting at 0 and an increment() method. Increment it twice, then print value.

Reveal one possible solution +
one_possible_solution.py
class Counter:
    def __init__(self):
        self.value = 0

    def increment(self):
        self.value += 1

counter = Counter()
counter.increment()
counter.increment()
print(counter.value)

05 Check your signal

QUICK SIGNAL CHECK

What does self refer to inside an instance method?

THAT’S ANOTHER IDEA IN YOUR TOOLKIT.

Experiment. Logged.

When you can explain the idea and make the example your own, mark it complete. Your log stays in this browser.

Keep exploring

Go deeper with the official Python guide ↗.

Built with curiosity. By Navan Sami. ↗Python 3 · Think. Try. Build.