Python @classmethod

Python classmethod() function is used to transform a method into a class method.

A class method can be called on the class or not he instance of the class.

In this tutorial, we will learn about the syntax of Python @classmethod decorator, and learn how to use this decorator in a class with the help of examples.

Syntax

The syntax of @classmethod decorator is

class C:
    @classmethod
    def f(cls, arg1, arg2, ...): ...
ADVERTISEMENT

Example

In this example, we will use @classmethod decorator to define a class function for a class and call that method.

Python Program

class A:
    @classmethod
    def printMessage(cls, msg) :
        print(msg)

A.printMessage('Hello World')
A().printMessage('Good Morning')
Try Online

Output

Hello World
Good Morning

Conclusion

In this Python Tutorial, we have learnt the syntax of Python classmethod() builtin function, and also learned how to use this function, with the help of Python example programs.