Next / Previous / Contents / Shipman's homepage

26.5. Class methods

A class method is similar to a static method (see Section 26.4, “Static methods”), except that its first argument is always the class that contains the method.

To declare a class method, use a declaration of this general form:

    def methodName(cls, ...):

When this method is called, the first argument (cls) will be the class containing methodName.

There are two ways to call a class method: using its class C, or an instance i. These two general forms are:


In the first case, the class C is passed as the cls argument of the method. In the second case, the class of instance i is passed as the cls argument.

>>> class Jal(object):
...     @classmethod
...     def whatClass(cls, n):
...         print "cls={0} n={1}".format(cls, n)
...     def __init__(self, color):
...         self.color = color
>>> Jal.whatClass(5)
cls=<class '__main__.Jal'> n=5
>>> eunice=Jal('green')
>>> eunice.whatClass(17)
cls=<class '__main__.Jal'> n=17