Dremendo Tag Line

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

    def changeData(cls):

# Creating 2 objects
x = Record()
y = Record()

print('Before changing the value')

# Changing the value using Class Method changeData() by object x

print('After changing the value')


Before changing the value
After changing the value

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.