我只是尝试在 python 中进行多重继承。我想出了这个
class ParentOne:
def foo(self):
print("ParentOne foo is called")
class ParentTwo:
def foo(self):
print("ParentTwo foo is called")
class Child(ParentOne, ParentTwo):
# how is this working
def call_parent_two_foo(self):
super(ParentOne, self).foo()
# This does not work
def call_parent_foo(self):
super(ParentTwo, self).foo()
def call_super_foo(self):
super(Child, self).foo()
def foo(self):
print("Child foo is called")
if __name__ == "__main__":
child = Child()
child.foo()
child.call_super_foo()
child.call_parent_two_foo()
# child.call_parent_foo() #This gives the below error
# super(ParentTwo, self).foo()
# AttributeError: 'super' object has no attribute 'foo'
它给出以下输出
Child foo is called
ParentOne foo is called
ParentTwo foo is called
我对如何调用感到困惑super(ParentOne, self).foo()
在这种情况下进行评估。据我的理解ParentOne
类不知道其方法和属性ParentTwo
班级。 super 在多重继承的情况下如何工作
Python 在构建类时会构建方法解析顺序 (MRO)。 MRO 是always线性。如果 python 无法创建线性 MRO,那么ValueError
将被提高。在这种情况下,您的 MRO 可能如下所示:
Child -> ParentOne -> ParentTwo -> object
现在当 python 看到一个super(cls, self)
,它基本上着眼于self
并计算出 MRO。然后它使用cls
确定我们当前在 MRO 中的位置,最后返回一个委托给nextMRO 中的课程。所以,在这种情况下,一个super(Child, self)
调用将返回一个委托给的对象ParentOne
. A super(ParentOne, self)
类将返回一个委托给的对象ParentTwo
。最后一个super(ParentTwo, self)
调用将委托给object
。换句话说,你可以想到super
作为以下代码的更高级版本:
def kinda_super(cls, self):
mro = inspect.getmro(type(self))
idx = mro.index(cls)
return Delegate(mro[idx + 1]) # for a suitably defined `Delegate`
请注意,自从super(ParentTwo, self)
返回一个“委托”给object
,我们可以明白为什么你会得到一个AttributeError
当你尝试时super(ParentTwo, self).foo()
——具体原因是因为object
has no foo
method.
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)