The build crew's checklist
Constructors
The analogy
Before anyone moves in, the crew runs a checklist: pour the foundation, set the address, pick the paint. The constructor is that checklist — it runs exactly once, the moment the house is built, and guarantees nothing is missing.
Visualizer
The build checklist
step 1 / 7CONSTRUCTOR CHECKLIST — runs once
1. allocate memory for the object
2. validate the arguments
3. assign colour
4. assign address
5. mark the object ready
new House("white", "12 Elm St") is called. Nothing exists yet.
class House:
def __init__(self, colour, address):
if not colour:
raise ValueError("a house needs a colour")
self.colour = colour
self.address = address
self.ready = True # invariants now hold
# __init__ runs once, at creation. Never again.Check yourself
How often does a constructor run per object?