How to : What are python class variables ?

In Python we have class variables, they are not defined in any methods. They are defined at class level. The only advantage of a class variable is it stays with class. If you instantiate your class and created an object, still with object you can access the class_variable.

In [1]: class A(object):
   ...:     class_var = 10
   ...:     def __init__(self):
   ...:         A.class_var = 20
   ...: 

In [2]: a = A()

In [3]: a.class_var
Out[3]: 20

In [4]: A.class_var
Out[4]: 20
But if you use self and defined another variable with same name, then you will have two variables. You can still access using class and another you can access using your new object.

In [5]: class B(object):
   ...:     class_var = 10
   ...:     def __init__(self):
   ...:         self.class_var = 40
   ...: 

In [6]: b = B()

In [8]: b.class_var
Out[8]: 40

In [9]: B().class_var
Out[9]: 40

In [10]: B.class_var
Out[10]: 10

In [11]: 
  
The sample code and outputs, hope they will help you understand their flow. Thank you. Raja G

0 comments:

Post a Comment