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?
A static method doesn't have access to the class and instance variables because it does not receive an implicit first argument like self and cls . Therefore it cannot modify the state of the object or class. The class method can be called using ClassName. method_name() as well as by using an object of the class.
Static means, that the member is on a class level rather on the instance level. Static variables exist only on class level and aren't instantiated. If you change a static variable in one instance of the class, the change will affect its value in all other instances.
Access the static variable using the same class object We can directly access a static variable in Python using the same class object with a dot operator. Let's consider a program to access the static variable in Python using the same class object. msg = 'This is a good Car. '
Yes, definitely possible to write static variables and methods in python. Static Variables : Variable declared at class level are called static variable which can be accessed directly using class name.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With