How To Define A Class Method In Python

In this tutorial, we will learn how to define a class method in Python. A class method is a method that is bound to a class and not an instance of the class. It can be used to modify the state of the class, instead of modifying the state of an instance object.

Class methods are often used for tasks that are related to the class itself rather than the instances of the class.

Step 1: Define a Class

First, let’s create a simple Python class called Employee. This class will have three attributes: name, age, and city. Define the class using the class keyword followed by the class name, and then define the class attributes inside the constructor method, which is called init.

Step 2: Create an Instance Method

Now, let’s create an instance method called display(). This method will display the details of an employee instance.

Step 3: Define a Class Method

To define a class method, we must use the @classmethod decorator. This decorator tells Python that the function below is a class method, and it should be bound to the class rather than an instance of the class.

In this example, let’s create a class method called from_string() that will create a new instance of the Employee class from a string containing the three attributes separated by commas.

In the class method definition, we use the @classmethod decorator immediately before the method definition. Inside the method, we use cls instead of self as the first parameter. The cls is a convention that stands for the class itself, although you can use any name you prefer.

Step 4: Testing the Class Method

Now, let’s test the class method by creating two instances of the Employee class using different methods:

Notice how we created the first instance using the regular constructor method, and the second instance using the class method from_string(). When we run this code, the following output is displayed:

John Doe, 30 years old, from New York
Jane Doe, 25 years old, from Los Angeles

Here is the full code for this tutorial:

Conclusion

In this tutorial, we learned how to define a class method in Python using the @classmethod decorator. We demonstrated how to create a class, add an instance method, define a class method, and use it to create instances of the class. Class methods provide a way to perform actions that are related to the class itself instead of an instance of the class.