Class Methods in Python Programming
OOPs in Python
In this lesson, we will understand what is Class Method in Python Programming and how to create them along with some examples.
What are Class Methods in Python?
Class Methods are used to access and modify the values stored in class variables. These methods are written using @classmethod decorators above them.
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 a class method, this will cause a TypeError while executing the program.