Classes

Classes

Classes bundle data and behavior into new object types.

Define a class when data and behavior should travel together. The initializer gives each object its starting state.

Source

class Counter:
    def __init__(self, start=0):
        self.value = start

first = Counter()
second = Counter(10)
print(first.value)
print(second.value)

Output

0
10
instanceCLASSClassTYPEtype
Every Python value sits on the instance → class → type triangle; the metaclass is the type of the class.

Methods are functions attached to the class. self is the particular object receiving the method call, so separate instances keep separate state.

Source

class Counter:
    def __init__(self, start=0):
        self.value = start

    def increment(self, amount=1):
        self.value += amount
        return self.value

first = Counter()
second = Counter(10)
print(first.increment())
print(second.increment(5))

Output

1
15

A name defined directly on the class body is a class attribute, shared by every instance. Reading falls back to the class when the instance has no attribute of that name; assigning to the class itself changes the value for every instance at once.

Source

class Counter:
    step = 1

    def __init__(self, start=0):
        self.value = start

first = Counter()
second = Counter()
print(first.step)
Counter.step = 5
print(second.step)

Output

1
5

A mutable class attribute is shared mutable state — the classic footgun. Define per-instance containers in __init__ so each object owns its own copy.

Source

class Cart:
    items = []

    def add(self, item):
        self.items.append(item)

shared_a = Cart()
shared_b = Cart()
shared_a.add("apple")
print(shared_b.items)

class FixedCart:
    def __init__(self):
        self.items = []

    def add(self, item):
        self.items.append(item)

own_a = FixedCart()
own_b = FixedCart()
own_a.add("apple")
print(own_b.items)

Output

['apple']
[]

Notes

See also

Run the complete example

Example code

Expected output

0
10
1
15
1
5
['apple']
[]

Execution time appears here after you run the example.