Skip to main content

classmethod()

The classmethod() function in Python returns a class method for the given function. A class method receives the class itself as the first argument, instead of an instance. This allows the method to access and modify the class state, rather than the instance state. Class methods are defined using the @classmethod decorator. They are commonly used for alternative constructors and for methods that manipulate the class itself.

Parameter Values

Parameter Description
function

A function that is to be converted into a class method.

Return Values

The classmethod() can return an instance of the class, None, a data type, or a complex object.

How to Use classmethod() in Python

Example 1:

The classmethod() function returns a method that can be called on the class itself rather than an instance of the class.

class MyClass:
    @classmethod
    def class_method(cls):
        return 'This is a class method'

# Calling the class method
MyClass.class_method()
Example 2:

The classmethod() can be used as a decorator in Python to define a method that operates on the class itself rather than instances of the class.

class MathOperations:
    @classmethod
    def add(cls, a, b):
        return a + b

# Calling the class method
result = MathOperations.add(5, 3)
print(result)
Example 3:

The classmethod() is often used in Python when you want a method to be associated with the class and not any specific instance of the class.

class Person:
    count = 0

    @classmethod
    def increment_count(cls):
        cls.count += 1

# Incrementing count using the class method
Person.increment_count()
print(Person.count)