在Python中调用基类的类方法
考虑以下代码:
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
如何从 Derived.do
调用 Base.do
?
如果这是一个普通的对象方法,我通常会直接使用 super
甚至直接使用基类名称,但显然我找不到在基类中调用类方法的方法。
在上面的示例中,Base.do(a)
打印 Base
类而不是 Derived
类。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
如果您使用的是新式类(即从 Python 2 中的
object
派生,或者始终在 Python 3 中),则可以使用super()
来实现,如下所示:这是您从派生类调用方法的基类版本中的代码(即
print cls, a
)的方法,其中cls
设置为派生类。If you're using a new-style class (i.e. derives from
object
in Python 2, or always in Python 3), you can do it withsuper()
like this:This is how you would invoke the code in the base class's version of the method (i.e.
print cls, a
), from the derived class, withcls
being set to the derived class.这已经有一段时间了,但我想我可能已经找到了答案。当您将方法修饰为类方法时,原始未绑定方法存储在名为“im_func”的属性中:
this has been a while, but I think I may have found an answer. When you decorate a method to become a classmethod the original unbound method is stored in a property named 'im_func':
基于 @David Z 的答案,使用:
可以进一步简化为:
我经常使用类方法来提供构建对象的替代方法。在下面的示例中,我使用上面的超级函数来加载类方法,以改变对象的创建方式:
输出:
Building on the answer from @David Z using:
Which can be further simplified to:
I often use classmethods to provide alternative ways to construct my objects. In the example below I use the super functions as above for the class method load that alters the way that the objects are created:
Output:
这对我有用:
This works for me: