Class Body Execution — ELI5
Imagine you write a recipe card. In most cases, the recipe just sits there on paper — nothing happens until someone decides to cook.
But Python’s class definitions are different. When Python reads the code inside a class block, it runs that code immediately, right then and there. It’s like the recipe card reads itself out loud the moment you finish writing it.
What Does “Runs Immediately” Mean?
When you write:
class Dog:
sound = "Woof"
print("The Dog class is being created!")
That print line runs the moment Python reads the class — before you ever create a dog. You’ll see “The Dog class is being created!” appear in your terminal as soon as the program hits that line.
Why Does It Work This Way?
Python needs to know what’s inside the class before it can create it. So it executes the class body like a little script, collects everything that was defined (variables, functions, etc.), and then packages it all up into a class object.
Think of it like a building inspection. Before the building exists, the inspector walks through the blueprints, checks every room, and signs off. The execution of the class body is that walk-through — it happens before the class “building” is officially ready.
A Fun Surprise
This means you can put any Python code inside a class body — loops, conditions, even function calls. It all runs during class creation:
class WeirdClass:
numbers = [x * 2 for x in range(5)]
if True:
greeting = "hello"
Those numbers and greeting become class attributes, computed on the spot.
One thing to remember: Python’s class body runs immediately at definition time, like a script that builds the class piece by piece before anyone creates an instance.
See Also
- Python Attribute Lookup Chain How Python finds your variables and methods — like checking your pockets, then your bag, then your locker, in a specific order every time.
- Python Bytecode And Interpreter How your .py file turns into tiny instructions the Python interpreter can execute step by step.
- Python Data Model Customization How Python lets your objects behave like built-in types — adding, comparing, looping, and printing, all with special methods.
- Python Garbage Collection See how Python cleans up unreachable objects, especially the tricky ones that point at each other.
- Python Gil Why Python threads can feel stuck in traffic, and how the GIL explains the behavior.