Skip to main content

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
Submitted by devanshi.srivastava on July 26, 2021

Devanshi, is working as a Data Scientist with iVagus. She has expertise in Python, NumPy, Pandas and other data science technologies.

About

At ProgramsBuzz, you can learn, share and grow with millions of techie around the world from different domain like Data Science, Software Development, QA and Digital Marketing. You can ask doubt and get the answer for your queries from our experts.