Python variable types

The variables which are written inside a class are of 2 types:

  • Instance variables
  • Class variables or Static variables

Instance variables are the variables whose separate copy is created in every instance (or object). For example, if 'x' is an instance variable and if we create 3 instances, there will be 3 copies of 'x' in these 3 instances. When we modify the copy of 'x' in any instance, it will not modify the other two copies.

A Python program to understand instance variables.

A Python program to understand class variables or static variables.

A method by the name 'modify' is used to modify the value of 'x'. This method is called 'class method' since it is acting on the class variable. To mark this method as class method, we should use built-in decorator statement @classmethod.

For Example,

A class method contains first parameter by default as 'cls' with which we can access the class variables. For example, to refer to the class variable 'x', we can use 'cls.x'. We can also write other parameters in the class method in addition to the 'cls' parameter.

We can access the class variables using the class methods as: cls.variable. If we want to access the class variables from outside the class, we can use: classname.variable, e.g. Sample.x.