Python classes and objects
Give each object its own state and methods.
Python
class Counter:
def __init__(self):
self.value = 0
def increment(self):
self.value += 1
first = Counter()
second = Counter()
first.increment()
first.increment()
print(first.value, second.value)
assert second.value == 0Output
2 0
Explanation
A class defines behavior for instances. Calling the class creates an object and invokes __init__ to initialize it. self refers to the instance whose method is running.
Instance attributes belong to one object. Incrementing first does not increment second; both instances were initialized independently.
Explore the dry run
Guided walkthroughReady
1
class Counter:2
def __init__(self):3
self.value = 04
def increment(self):5
self.value += 16
7
first = Counter()8
second = Counter()9
first.increment()10
first.increment()11
print(first.value, second.value)12
assert second.value == 0Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Create the first instance and run its initializer. | first.value = 0 | — | |
| Create an independent second instance. | first.value = 0, second.value = 0 | — | |
| The first increment call updates first. | first.value = 1 | — | |
| The second increment call updates the same instance. | first.value = 2, second.value = 0 | — | |
| Read both objects. | first.value = 2, second.value = 0 | 2 0 |
Cost and common mistakes
O(1) work per increment, with one value per object.
- A mutable class attribute would be shared; create per-instance collections in __init__.
- Methods need the instance parameter, conventionally named self.
Try it yourself
Increment second once, then print both values.
Reveal answer and reasoning
The result is 2 1 because each object keeps its own value.