【发布时间】:2014-07-07 22:55:25
【问题描述】:
我想在 Python 2 中使用 super() 调用父类方法。
在 Python 3 中,我会这样编码:
class base:
@classmethod
def func(cls):
print("in base: " + cls.__name__)
class child(base):
@classmethod
def func(cls):
super().func()
print("in child: " + cls.__name__)
child.func()
这个输出:
in base: child
in child: child
但是,我不知道如何在 Python 2 中做到这一点。当然,我可以使用 base.func(),但我不喜欢另外指定父类名称,主要是我得到了不需要的结果:
in base: base
in child: child
使用cls (cls is child) 作为super() 函数调用中的第一个参数,我收到此错误:
TypeError: must be type, not classobj
知道如何使用super() 或我不必指定父类名称的类似函数吗?
【问题讨论】:
-
提示:复制粘贴你的问题到谷歌搜索
标签: python inheritance parent-child superclass super