Python classes and objects
Give each object its own state and methods.
On this page
Functions, parameters, and assignment.
- Give each object its own state and methods.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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 == 02 0
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
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 == 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 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
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.