Classes
Classes
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
10Methods 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
15A 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
5A 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
selfis the instance the method is operating on.__init__initializes each new object.- Class attributes are shared across instances; instance attributes belong to one object.
- Put mutable defaults in
__init__, not on the class body. - Use classes when behavior belongs with state; use dictionaries for looser structured data.
See also
- related: Inheritance and Super
- related: Classmethods and Staticmethods
- next depth: Bound and Unbound Methods
- related: Dataclasses
Run the complete example
Expected output
0
10
1
15
1
5
['apple']
[]
Execution time appears here after you run the example.