Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When are python class properties created

Tags:

python

class Foo:
   bar = 1
   ......etc.

I know when creation a instance, bar is created before __init__, I want to know if it is the very first thing to create the bar property when creating a instance for Foo. Also, does the bar already exists in memory before any instance is created?

like image 376
Robert Bean Avatar asked Feb 26 '26 14:02

Robert Bean


1 Answers

Remember that in Python class is an executable statement (as too are def and import). So the answer to your question is that bar is created when the class statement executes.

Specifically, when a class statement executes, the body of the class is executed in a namespace that is usually just a dict. When the body has finished executing a class object is created with a copy of the resulting dict as the __dict__ attribute for the class. The dict at this point contains all the names bound inside the class body bar=1 for example, but also any functions that were defined in the class body.

Instances, when they are created, don't get a copy of bar, they just refer back to the class. When you lookup a name on an instance Python looks in both the instance's __dict__ and the class's __dict__.

like image 102
Duncan Avatar answered Mar 01 '26 03:03

Duncan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!