Hello folks...!!!!
Today let us look at class variables.
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:
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.
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.
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 :
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 :
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
Post a Comment