Python classmethod() with Examples

Python-classmethod.jpg

In Python, methods can be declared at the class level and the instance level. How do you declare a method at the class level, and what exactly are class methods in Python? classmethods in Python provide a way to define methods that are bound to the class itself rather than an instance. Unlike regular instance methods that operate on individual objects, class methods receive the class as their first argument, allowing them to access or modify class state and create alternative constructors. In this guide, we will explore class methods in Python, what they are, how they differ from static methods, and why they are useful.

Table of Contents:

What are Class Methods?

A class method in Python is a method bound to the class and not to the instance of the class. It can access and modify the class-level data that is shared by all the instances by using the cls parameter. It is defined using the @classmethod decorator above a method in the class, and its first parameter has to be named as cls (short for class). They are used to work with the class instead of objects, as they can change or use class variables, which help create new objects in a different way.

Master Python Today - Accelerate Your Future
Enroll Now and Transform Your Future
quiz-icon

Key Features of Class Methods

Some of the key features of the class methods in Python are as follows:

  • Class methods work with the class, not with the objects of the class.
  • They have cls as their first parameter.
  • They are shared by all instances of the class.
  • They can be used to create objects using alternative constructors.
  • They support the principle of inheritance.

Syntax of the classmethod in Python

Below is the syntax of the classmethod in Python.

@classmethod
def method_name(cls, ...):
    # method body

In the above syntax,

  • @classmethod is the decorator that tells Python that the method is a class method.
  • method_name(cls, …): is the method taking cls as the first argument

For example,

Syntax of the classmethod in Python

In the above figure, Learn is the name of the class having the method choose_subject(), which is represented with the @classmethod. The three boxes are the options that the class method can return or work with.

Python

Output:

Syntax of the classmethod

Explanation: In the above code, the subject ‘Physics’ is chosen, hence the output appears as above.

Class Method vs Static Method

A class method is used to access or modify the class’s state or to create an alternative constructor. It receives the class itself as a first parameter and is defined using the @classmethod decorator. While a static method does not receive any parameter like self or cls. It is defined with the @staticmethod decorator and behaves like a regular function. They cannot access or modify the class or instance data.

Now, let us discuss the key differences between class methods and static methods in tabular form.

Feature Class Method Static Method
Decorator @classmethod @staticmethod
First Parameter Receives the class as the first parameter (cls) Does not receive any automatic first argument
Access to class data Can access class data Cannot access class or instance data
Binding Bound to the class Not bound to class or instance
Typical signature def method(cls, …) def method(…)

Python classmethod() Function

classmethod() is a built-in function in Python that converts a method into a class method. It takes the first argument as its class rather than an instance of the class, which allows the method to access or modify the class state and call the other methods also. It is used when you want a method to work with the class itself rather than its instance. It lets you convert a simple function into a class method.

Parameters of classmethod()

A variable used in a function definition to represent the input that the function expects when it is called. The classmethod() in Python takes exactly one parameter, i.e., the function which you want to turn into a class method.

Arguments of classmethod()

Arguments are the actual values that are passed into a function when you call it. classmethod() in Python uses a special type of argument called cls, which stands for class, not an instance of the class.

Return Value of classmethod()

The classmethod() function in Python returns a class method object.

Syntax of the classmethod() in Python

Below is the syntax of the classmethod() in Python.

classmethod(function)
  • function is defined inside the same class, without a self parameter.

Example:

Python

Output:

Syntax of the classmethod() in Python

Explanation: In the above program, a class named Course with a class variable course_name is initially set to DSA. After that, a class decorator @classmethod is used above the function def change_course_name(cls, new_course). The function is called having the argument Cloud, hence the output is first printed as DSA and then Cloud.

Factory Method Using a classmethod()

A factory method is a method that returns a class object when you want more control over how objects in Python are created. It is an alternative to a constructor and is created using a @classmethod. It is used when you want to create a class object from different data sources or formats. For example. You receive data in various formats, now, instead of parsing and converting this data outside the class and then manually creating objects, you can define a class method (factory method) to handle the parsing and object creation inside the class.

It keeps the object logic encapsulated and makes the code cleaner and reusable.

Example:

Python

Output:

Factory Method

Explanation: In the above program, the class Employee is created, and then the factory method def from_string(cls, emp_str) creates an instance using a string. This method splits the string passed as an argument and returns the employee’s name and their salary as an integer.

Get 100% Hike!

Master Most in Demand Skills Now!

How Does the Class Method Work for Inheritance?

Inheritance means one class can use the properties and methods of another class. For example, Dog and Cat can inherit from a common parent class, Animal. If a child uses a class method inherited from the parent, the cls parameter inside that method will automatically refer to its child.

It means that:

  • You can define a class method once in the parent class.
  • All child classes can use it.
  • It will automatically create an object of the correct class (the child that called it).

When a class method is defined in a parent class and is called from its child class, Python will automatically pass the child as the cls parameter, not the parent class, where the method was defined.

Example:

Python

Output:

How Does the Class Method Work for Inheritance

Explanation: In the above example, the class Animal sets the name attribute and a class method called create, which takes a name as input and returns a new object using cls(name). The classes Dog and Cat are inherited from the class Animal, having their own function speak.

Python @classmethod Decorator

A decorator in Python is a special type of function used to modify another function, method, or class without changing its actual code. The @classmethod decorator is used to define a class method that is bound to the class and not the instance of the class, i.e., it can access and modify the class-level attributes that are shared across the objects.

When a method is defined using the @classmethod decorator, Python passes the class itself as the first argument to the method.

Syntax of classmethod Decorator

Below is the syntax of the @classmethod decorator in Python.

class MyClass:
@classmethod
def my_class_method(cls, arg1, arg2):
# method body
pass
  • MyClass is the name of the class
  • my_class_method is the name of the method
  • cls, arg1, and arg2 are the arguments of the method

Example:

Python

Output:

classmethod Decorator

Explanation: In the above program, @classmethod is a Python decorator used to define a method. It takes cls as the first parameter instead of self. The company_name variable is changed and is displayed.

What is the Difference Between self and classmethod?

The self keyword in Python is used in an instance method and refers to the current object of the class. It also allows access to the object attributes. While a @classmethod uses a cls as its first parameter and refers to the class itself, not bound to a specific object.

Now, let us discuss the key difference between self and classmethod in a tabular form.

Aspect self (Instance Method) classmethod (@classmethod)
First Parameter self cls
Access Can access instance attributes and methods Can access or modify class-level attributes
Binding Bound to the object or instance of the class Bound to the class only
Called Using Called by an object Called by class or object

Dynamically Delete Class Methods

In Python, you can dynamically delete class methods using the delattr() function or by using the del statement. It has the following syntax,

delattr(ClassName, "method_name")

OR

del ClassName.method_name

Example:

Python

Output:

Dynamically Delete Class Methods

Explanation: In the above example, MyClass.greet is called and it works correctly, after that, it is deleted by using the delattr() method, and when called again, it raises an exception.

Unlock Your Future in Python
Start Your Python Journey for Free Today
quiz-icon

Conclusion

From the above article, we learned that Python class methods are built-in functions used to access or modify the class state and call other methods. It takes one parameter and a special type of argument called a cls, and returns a class method object. A Python classmethod makes the code reusable with the help of inheritance, as it allows the child class to inherit the methods and functions of the parent class.

If you want to learn more about the Python classmethod in detail, you can refer to our Python course.

Python classmethod – FAQs

Q1. How to call a classmethod in Python?

To use a class method in Python, define it using @classmethod, then call it using the class name or an instance; both will work.

Q2. What is the purpose of the classmethod in Python?

It lets you access and modify class-level data and is often used for factory methods.

Q3. What is a global variable in a Python classmethod?

A global variable is defined outside all functions or classes and can be accessed inside a class method using the global keyword.

Q4. What is the difference between a classmethod and a normal method in Python?

A normal method takes self and works with instances of the class, while a class method takes cls and works with the class itself.

Q5. What are methods and static methods in Python?

Methods work on object instances and use self, while static methods don’t use self or cls and behave like plain functions inside a class.

About the Author

Senior Consultant Analytics & Data Science, Eli Lilly and Company

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

EPGC Data Science Artificial Intelligence