Calling a base class's classmethod in Python
考虑以下代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do(a) if __name__ == '__main__': d = Derived() d.do('hello') > $ python play.py > In derived! > <class '__main__.Base'> msg |
从
如果这是一个普通的对象方法,我通常会直接使用
在上面的例子中,
如果您使用的是一个新样式的类(即在python 2中派生自
1 | super(Derived, cls).do(a) |
这就是如何从派生类调用基类版本的方法(即
这已经有一段时间了,但我想我可能找到了答案。当您将方法修饰为ClassMethod时,原始未绑定方法存储在名为"im_func"的属性中:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | class Base(object): @classmethod def do(cls, a): print cls, a class Derived(Base): @classmethod def do(cls, a): print 'In derived!' # Base.do(cls, a) -- can't pass `cls` Base.do.im_func(cls, a) if __name__ == '__main__': d = Derived() d.do('hello') |
这对我很有用:
1 | Base.do('hi') |