How it works
A class is a template; an instance is one object built from it. The initialiser runs at construction and sets up instance state.
Give every attribute a value in the initialiser so no instance starts half-built.
Common error
Forgetting the instance parameter on a method, which produces a confusing argument-count error.
Worked example
Python
class Counter:
def __init__(self, start):
self.value = start
def increment(self):
self.value += 1
a = Counter(2)
b = Counter(10)
a.increment()
print(a.value, b.value)Output
3 10Each instance holds its own value. self identifies the instance receiving a method call; calling a.increment changes a rather than b.
Exercises
4.1.1 · Explain
What role does __init__ play when Counter(5) is evaluated?
Show solution
It initializes the new instance state using the supplied argument. It should not return an alternate object or a non-None result.
4.1.2 · Write code
Create a Box class whose constructor stores width and whose area method returns width squared. Show Box(4).area().
Show solution
Store instance state through self.
One valid solution
class Box:
def __init__(self, width):
self.width = width
def area(self):
return self.width ** 2
print(Box(4).area())Expected output
16