Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing static properties in Python

Tags:

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 statically and through a MyClass instance?

like image 767
Andre Avatar asked Jul 05 '10 12:07

Andre


People also ask

How do you access a static method in python?

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.

What is static property in python?

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.

How do I find static variables in python?

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. '

Can we have static variable in python?

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.


1 Answers

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.

like image 126
unutbu Avatar answered Sep 25 '22 00:09

unutbu