classmethod是一个装饰器,包装一个函数,你可以在一个类或(等效地)一个实例上调用结果对象:
>>> class x(object):
... def c1(*args): print 'c1', args
... c1 = classmethod(c1)
... @classmethod
... def c2(*args): print 'c2', args
...
>>> inst = x()
>>> x.c1()
c1 (,)
>>> x.c2()
c2 (,)
>>> inst.c1()
c1 (,)
>>> inst.c2()
c2 (,)
如您所见,无论是直接定义还是使用装饰器语法定义,无论是在类还是实例上调用它,classmethod总是接收类作为其第一个参数.
classmethod的主要用途之一是定义替代构造函数:
>>> class y(object):
... def __init__(self, astring):
... self.s = astring
... @classmethod
... def fromlist(cls, alist):
... x = cls('')
... x.s = ','.join(str(s) for s in alist)
... return x
... def __repr__(self):
... return 'y(%r)' % self.s
...
>>> y1 = y('xx')
>>> y1
y('xx')
>>> y2 = y.fromlist(range(3))
>>> y2
y('0,1,2')
现在如果你继承y,那么classmethod继续工作,例如:
>>> class k(y):
... def __repr__(self):
... return 'k(%r)' % self.s.upper()
...
>>> k1 = k.fromlist(['za','bu'])
>>> k1
k('ZA,BU')