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:
@classmethod
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 , or an instance C. These two general
forms are:
i
C.methodName(...)i.methodName(...)
In the first case, the class is passed as the Ccls
argument of the method. In the second case, the class of
instance is
passed as the icls 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