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 (<class '__main__.x'>,)
>>> x.c2()
c2 (<class '__main__.x'>,)
>>> inst.c1()
c1 (<class '__main__.x'>,)
>>> inst.c2()
c2 (<class '__main__.x'>,)
如您所见,无论是直接定义它还是使用装饰器语法定义它,以及在类或实例上调用它,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
,则类方法将继续工作,例如:
>>> class k(y):
... def __repr__(self):
... return 'k(%r)' % self.s.upper()
...
>>> k1 = k.fromlist(['za','bu'])
>>> k1
k('ZA,BU')