Python · Course navigation

Python classes and objects

Give each object its own state and methods.

On this page
Before you start

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

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 == 0
Output
2 0

Follow the code

Open the walkthrough to inspect the example one step at a time.

Show guided walkthrough
Guided walkthroughReady
1class Counter:
2 def __init__(self):
3 self.value = 0
4 def increment(self):
5 self.value += 1
6
7first = Counter()
8second = Counter()
9first.increment()
10first.increment()
11print(first.value, second.value)
12assert second.value == 0

Follow 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
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput 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.

Further reading