codescracker
python

Python classmethod Decorator - @classmethod



« Python Tutorial Python Examples »

The class method decorator or @classmethod is used to define methods inside a class as class methods. For example:

class CodesCracker:
    @classmethod
    def classfun(cls, x):
        print("The first parameter (cls):", cls)
        print("The second parameter (x):", x)

CodesCracker.classfun("Hey!")

Here is the output produced by above Python program, demonstrating the @classmethod decorator:

The first parameter (cls): <class '__main__.CodesCracker'>
The second parameter (x): Hey!

The class methods have reference to the class object as first argument.

Class methods have access to what the class is. The class method is also a function, but with access to the object and its internals like fields and other methods, where as static methods haven't. The differentiation between these two is provided in class method Vs static method in Python.

The class methods can be called either directly, using:

ClassName.ClassMethodName()

Or by using an object of the class, in this way:

ob = ClassName()
ob.ClassMethodName()

where ob is a variable refers to the object of the class ClassName.

In the above example program, using the following statement:

CodesCracker.classfun("Hey!")

The class CodesCracker gets implicitly passed as the first parameter of class method named classfun() whereas the "Hey!" will get passed as second parameter of class method named classfun(). That is, the cls parameter (the first parameter) while defining class methods using the @classmethod decorator, refers to the class itself.

Python @classmethod Decorator Syntax

The syntax of @classmethod decorator in Python is:

@classmethod
def myfun(cls, arg1, arg2, arg3, ..., argN):
    # definition code goes here

Just like self, the first parameter of normal method inside a class refers to the object instance. In case of class methods too, the first parameter of class method, that is cls inside a class, refers to the class itself. And rest of all the parameters like arg1, arg2, and so on refers to the arguments like normal functions have`.

Python @classmethod Decorator Example

Here is an example of @classmethod decorator in Python:

class CodesCracker:
    @classmethod
    def myfun(cls, x, y, z, str):
        print("The value of x:", x)
        print("The value of y:", y)
        print("The value of z:", z)
        print("The value of str:", str)

CodesCracker.myfun(100, 200, 300, "codescracker")

The snapshot given below shows the sample output produced by above Python program, demonstrating the @classmethod decorator:

python classmethod decorator

Python Online Test


« Python Tutorial Python Examples »



© Copyright 2021. All Rights Reserved.

CodesCracker