Python: The @classmethod Decorator

The @classmethod decorator, is a built-in function decorator. It is used to declare a method within class method. It is also used to declare a factory method that returns objects of the class.

It can be called by using ClassName.MethodName().

It is an expression that gets evaluated after function is defined. The result of this evaluation shadows function definition. It can return an object of the class. It can access the class attributes but not the instance attributes.

Syntax:

class abc (object):
    @classmethod
    def func(cls, arg1, arg2, ...):
       ........

Example:

class abc:
    @classmethod
    def func(cls,a,b):
        c=a+b
        print("The answer is:",c)
    
        
abc.func(2,5)  

Output: The answer is: 7

Tags