It is possible to define behavior that is linked to the class rather than an individual object; this behavior is defined in a class method using @classmethod decorator.

classmethod annotation

Class methods are written in a similar manner to any other method but are decorated with @classmethod decorator and take a first parameter which represents the class rather than an individual instance. This decoration is written before the method declaration.

An example of a class method is shown below:

class Account:
    """ An example class to hold a Account detail"""
    instance_count = 0

    @classmethod
    def increment_instance_count(cls):
        cls.instance_count += 1

    def __init__(self, number):
        Account.increment_instance_count()
        self.number = number

In this case the class method increments the instance_count variable; note that the instance_count variable is accessed via the cls parameter passed into the increment_instance_count method by Python.

As this is a class method you do not need to prefix the class attribute with the name of class; instead the first parameter to the class method, cls, represents the class itself.

The class method can be accessed by prefixing it with the name of the class and using the dot notation to indicate which method to call. This is illustrated in the body of the __init__() method.

@classmethod role in Python

  • Instance creation – This role is very important as it is how you can use a class as a factory for objects and can help hide a whole load of set up and instantiation work.
  • Answering enquiries about the class – This role can provide generally useful objects, frequently derived from class variables. For example, they may return the number of instances of this class that have been created.
  • Instance management – In this role, class-side methods control the number of instances created. For example, a class may only allow a single instance of the class to be created; this is termed a singleton class. Instance management methods may also be used to access an instance.
  • Testing – Class methods can be used to support the testing of an instance of a class. You can use them to create an instance, perform an operation and compare the result with a known value. If the values are different, the method can report an error. This is a very useful way of providing regression tests.

Conclusion

In this article, we saw about how to use class method and what is the purpose of using the class method in Python.

Reference

https://docs.python.org/3/library/functions.html#classmethod