/  Technology   /  static class variable.

static class variable.

Are static class variables possible in Python?

Yes. Class or static variables are quite distinct from any other member variables having the same name. When we declare a variable inside a class but outside any method, it is called a class or static variable. Class or static variables can be referred through a class but not directly through an instance. In other words, Static variables are those which belong to the class and not the objects. The static variables are shared amongst the objects of a class. In the class declaration, all the variables which get assigned by a value are class variables. And instance variables are those which get assigned to values inside class methods.

 

We don’t have a special keyword in Python for creating static variables. Python follows a simple way for defining static variables.

>>class Color:

pik = ‘Chromatics’                      # class or static variable

def __init__(self, variety):

   self.var = variety  # instance variable

 

 # method to show data

def show(self):

   print(‘Color is of category: ‘, Color.pik)          #accessing class variable

   print(‘And color is: ‘, self.variety)            # accessing instance variable

 

>>r = Color(‘Red’)

>>p = Color(‘Purple’)

>>g = Color(‘Green’)

>>r.show()

>>p.show()

>>g.show()

 

Output:

Color is of category:  Chromatics

And color is:  Red

Color is of category:  Chromatics

And color is:  Purple

Color is of category:  Chromatics

And color is:  Green

 

Here, pik is a class variable as it is defined inside the ‘class definition’ and is not in any of the ‘class methods’ and variety is an instance variable as it is defined inside a ‘method’.

The variable pik is referenced using the class name Shape while the variable variety is referenced using the different object references.

In the program above, we have different colour objects each are of them are of different types but belong to Chromatics, so each object of a class belong to the same category(here Chromatics) which is the class variable and variable variety is an instance variable as it is different for all the objects.

 

 

Leave a comment