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 statically and through a MyClass instance?
The code
creates a class
MyClasswhich has a dict:Notice the key-value pair
'Property1': 1.When you say
MyClass.Property1, Python looks in the dictMyClass.__dict__for the keyProperty1and if it finds it, returns the associated value1.When you create an instance of the class,
a dict for the instance is also created:
Notice this dict is empty. When you say
mc.Property1, Python first looks inmc.__dict__for the'Property1'key. Since it does not find it there, it looks in the dict ofmc‘s class, that is,MyClass.__dict__.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.