Blueprints for behaviour.
Keep state and the operations that belong to it in one place.
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.
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)Orbit True
03 Under the hood
- 1
Calling Mission("Orbit") creates an instance, then __init__ sets its initial attributes.
- 2
finish() changes that instance’s completed attribute. A different Mission instance would have independent attributes assigned in its own __init__.
- 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
Create a Counter class with value starting at 0 and an increment() method. Increment it twice, then print value.
Reveal one possible solution +
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
What does self refer to inside an instance method?
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 ↗.