How to Use classmethod() Function in PythonPython Basics


The classmethod() method converts the given function into a class method.

Example

#!/usr/bin/python
# -*- coding: UTF-8 -*-

class temp(object):
    bar = 1

    def func1(self):
        print('foo')

    @classmethod
    def func2(cls):
        print('func2')
        print(cls.bar)
        cls().func1()

temp.func2()  # No instantiation is required

Output:

func2
1
foo

Syntax

classmethod(function)

Parameters

Name Description
function The function which is to be converted into a class method.

Return Value

It returns a class method for the given function.

© 2024 Cheerlearn.com, all rights reserved. Privacy Policy | Contact Us