Accessing static properties in Python
I am relatively new to Python and was hoping someone could explain the following to me:
class MyClass:
Property1 = 1
Property2 = 2
print MyClass.Property1 # 1
mc = MyClass()
print mc.Property1 # 1
Why can I access Property1 both staticall开发者_运维技巧y and through a MyClass instance?
The code
class MyClass:
Property1 = 1
creates a class MyClass
which has a dict:
>>> MyClass.__dict__
{'Property1': 1, '__doc__': None, '__module__': '__main__'}
Notice the key-value pair 'Property1': 1
.
When you say MyClass.Property1
, Python looks in the dict MyClass.__dict__
for the key Property1
and if it finds it, returns the associated value 1
.
>>> MyClass.Property1
1
When you create an instance of the class,
>>> mc = MyClass()
a dict for the instance is also created:
>>> mc.__dict__
{}
Notice this dict is empty. When you say mc.Property1
, Python first looks in mc.__dict__
for the 'Property1'
key. Since it does not find it there, it looks in the dict of mc
's class, that is, MyClass.__dict__
.
>>> mc.Property1
1
Note that there is much more to the story of Python attribute access. (I haven't mentioned the important rules concerning descriptors, for instance.) But the above tells you the rule for most common cases of attribute access.
精彩评论