Python多重继承
我有3个等级A、B和D,如下所示Python多重继承,python,Python,我有3个等级A、B和D,如下所示 class A(object): def test(self): print "called A" class B(object): def test(self): print "called B" class D(A,B): def test(self): super(A,self).test() inst_d=D() inst_d.test() -----------------
class A(object):
def test(self):
print "called A"
class B(object):
def test(self):
print "called B"
class D(A,B):
def test(self):
super(A,self).test()
inst_d=D()
inst_d.test()
----------------------------------------
Output:
called B
问题:在
D.test()
中,我正在调用super(A,self).test()
。即使方法A.test()
也存在,为什么只调用B.test()
。在D.test
中,您告诉它调用A的父级的测试方法-这就是super
所做的
通常,您希望在super
调用中使用当前类名。super(A,self)。test()
的意思是:在self
的方法解析顺序(mro)后调用对象的test
方法
使用D.\uuuuMRO\uuuuuuu
可以看到方法的分辨率顺序是:
<class '__main__.D'>, <class '__main__.A'>, <class '__main__.B'>, <type 'object'>
,
因此调用B
的test
在Python3中,您只需键入
super().test()
,它就会执行您想要的操作。在Python2中,您需要键入:super(D,self).test()
通常使用当前类名调用super,并且您可以让Python的MRO根据其遵循的算法确定应该调用哪个父类。因此,对于您想要的行为,您的代码将如下所示
class D(A,B):
def test(self):
super(D,self).test()
注意
super(D,self).test()
Python的super工作方式有些不明显。正确使用它的一个很好的实用指南是:另外,其他类也需要调用super()
,以获得MRO中的下一个类;跳转到方法解析顺序中随机位置的假设用例可能会很奇怪。答案有点不清楚-B
不是a
的父级,因此调用B.test()
的原因不太清楚。谢谢Daniel,在这种情况下,mro将从A的父级开始,而不是从类A开始。明白了。@Anoop:没错。super()
的第一个参数指示当前执行的方法在通过从第二个参数的类型开始构建的MRO中的位置。然后,通过结果代理调用的方法将是MRO中当前方法之后的下一个方法。