Class variables





Hello folks...!!!!
Today let us look at class variables.

Class variables :

The class variables are initialized while constructing the classes. They are common for every object created with the class. These variables are not associated with any specific object.

The value they hold is common for all the objects. They are accessed using the class name instead of writing as "self.variable_name". 

The variables which are specific to each object created are called as Instance variable. They are called so, because their values vary with objects created for the class.

The class variable values can be used for keeping track of number of objects created for the class or auto generation of roll-numbers/id for a product, etc.

Let us look at examples:

Counting objects :

class variable in python

Here cnt is the class variable. Instead of accessing it with "self.", we access it with class name as function.cnt. The value of the class variable is retained until the program is in execution.

Auto generating id for products :

class variables

Here id1 is the class variable. It is assigned to the instance variable pid which denotes the product id. The instance variable is accessed using self as usual and the class variable is accessed using the class name shop.


Next Topic👉

Comments