| [ Web Proxy ] |
| Viewing: https://www.pythonbyexample.dev/examples/classes | [Back] [Original] |
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
self is the instance the method is operating on.__init__ initializes each new object.__init__, not on the class body.0
10
1
15
1
5
['apple']
[]
Execution time appears here after you run the example.
| Web Proxy Viewer | New URL | Original Page |