Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/346.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python多重继承_Python - Fatal编程技术网

Python多重继承

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() -----------------

我有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()

----------------------------------------
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中当前方法之后的下一个方法。