在Python中调用基类的类方法 [英] Calling a base class's classmethod in Python
问题描述
请考虑以下代码:
class Base(object):
@classmethod
def do(cls,a):
print cls,a
class Derived(Base):
@classmethod
def do ,a):
print'In derived!'
#Base.do(cls,a) - 不能传递`cls'
Base.do(a)
if __name__ =='__main__':
d = Derived()
d.do('hello')
> $ python play.py
>在派生!
> < class'__main __。Base'> msg
从 Derived.do
我调用 Base.do
?
我通常会使用 super
甚至是基类名称,如果这是一个普通的对象方法,我找不到一种方法来调用基类中的classmethod。
在上述示例中, Base.do(a)
打印 Base
类而不是派生
类。
> super(Derived,cls).do(a)
EDIT :哦,等一下...你不清楚你要问什么。这是如何调用基类的方法版本中的代码,从派生类。
Consider the following code:
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
From Derived.do
, how do I call Base.do
?
I would normally use super
or even the base class name directly if this is a normal object method, but apparently I can't find a way to call the classmethod in the base class.
In the above example, Base.do(a)
prints Base
class instead of Derived
class.
super(Derived, cls).do(a)
EDIT: Oh, wait a minute... it's not clear exactly what you're asking. This is how you would invoke the code in the base class's version of the method, from the derived class.
这篇关于在Python中调用基类的类方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!