classmethod python
Posted by arnulfo on 2007/07/26
classmethod(function)
Returns a class method for function.
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:
@classmethod
def f(cls, arg1, arg2, ...): ...
The @classmethod form is a function decorator — see def for details.
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.
My personal experience is that I almost *never* want a staticmethod.
The things that I would have written as a staticmethod in Java I simply
write as a module-level function in Python.
I do occasionally used classmethods though to build alternate
constructors. I recently had a class with a constructor that looked like:
class C(object):
def __init__(self, *args):
…
I already had code working with this constructor, but I needed to add an
optional ‘index’ parameter. I found the clearest way to do this was
something like:
class C(object):
def __init__(self, *args):
…
@classmethod
def indexed(cls, index, *args):
…
obj = cls(*args)
obj.index = index
…
return obj
Then the classes that needed the ‘index’ parameter simply use
C.indexed() as the constructor instead of C().
STeVe