多继承执行顺序

时间:2015-10-30 03:34:18

标签: python python-2.x

代码1:

class base(object):
    def test(self):
        pass


class low1(object):
    def test(self):
        super(low1, self).test()
        print "low1 test"


class low2(object):
    def test(self):
        super(low2, self).test()
        print "low2 test"


class high(low1, low2, base):
    pass


if __name__ == "__main__":
    high().test()

码2:

class base(object):
    def test(self):
        pass


class low1(object):
    def test(self):
        # super(low1, self).test()
        print "low1 test"


class low2(object):
    def test(self):
        # super(low2, self).test()
        print "low2 test"


class high(low1, low2, base):
    pass


if __name__ == "__main__":
    high().test()

code1的输出是:

low2 test
low1 test

code2的输出是:

low1 test

当我为什么称为高对象的测试方法时,它执行low1和low2的测试方法?

1 个答案:

答案 0 :(得分:2)

查看方法解析顺序:

print(high.mro())

打印:

[<class '__main__.high'>, <class '__main__.low1'>, <class '__main__.low2'>,
 <class '__main__.base'>, <class 'object'>]

考虑super()含义&#34;接下来排在&#34;,其中line是上面显示的类列表。因此,super(low1, self)会找到low2作为下一行的类。