Python: classmethod() function

classmethod() function

The classmethod() function is used to convert a method into a class method.



A class method receives the class as implicit first argument, just like an instance method receives the instance. To declare a class method, use this idiom:

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

The @classmethod form is a function decorator. It can be called either on the class (such as C.f()) or on an instance (such as C().f()). The instance is ignored except for its class. If a class method is called for a derived class, the derived class object is passed as the implied first argument.


(Python 3.2.5)


Name Description Required /
function Function that needs to be converted into a class method Required

Return value:

Return a class method for function.

Example: Create class method using classmethod()

class Example:
    age = 55

    def printAge(cls):
        print('The age is:', cls.age)

# create printAge class method
Example.printAge = classmethod(Example.printAge)



The age is: 55

Pictorial Presentation:

Python: Built-in-function - classmethod() function

Python Code Editor:

Previous: chr()
Next: compile()

Test your Python skills with w3resource's quiz

Follow us on Facebook and Twitter for latest update.

Python: Tips of the Day

Maps the values of a list to a dictionary using a function, where the key-value pairs consist of the original value as the key and the result of the function as the value:


def tips_map_dictionary(itr, fn):
  ret = {}
  for a in itr:
    ret[a] = fn(a)
  return ret
print(tips_map_dictionary([2,4,6], lambda a: a * a))


{2: 4, 4: 16, 6: 36}


We are closing our Disqus commenting system for some maintenanace issues. You may write to us at reach[at]yahoo[dot]com or visit us at Facebook