Class Variables in Python Programming
OOPs in Python
In this lesson, we will understand what are Class Variables in Python Programming and how to create them along with some examples.
What are Class Variables in Python?
Variables shared between all the objects of a class are called Class Variables. We can access a Class Variable by class name or by using the object of the class using a dot (.) operator.
For example, if we create a class variable called data inside a class and then create four objects of that class, these four objects share the common variable data. If any of these objects change the value of the class variable data using a class method, the value of data gets changed in all the objects.
Example of creating a Class Variable in a Class
class Record: # This is a Class Variable data = 0
Example of changing value of a Class Variable using Class Method
class Record: data = 10 @classmethod def changeData(cls): cls.data=15 # Creating 2 objects x = Record() y = Record() print('Before changing the value') print(x.data) print(y.data) # Changing the value using Class Method changeData() by object x x.changeData() print('After changing the value') print(x.data) print(y.data)
Before changing the value 10 10 After changing the value 15 15
In the above program, we have created a class method called changeData() using the built-in decorator statement @classmethod.
To change the value of data inside the class method changeData(), we have to pass the first parameter by name cls, with which we can access and change the value of the class variable. The first parameter of a class method always refers to the memory address of the class itself.
The cls is not a keyword, we can use any name in place of cls for the first parameter, and the provided name will be used as a reference to the class itself.
If we don't provide the first parameter in the class method, this will cause a TypeError while executing the program.