多重继承执行顺序

multiple inheritance execution order

代码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

为什么调用high对象的test方法时,它同时执行了low1和low2的test方法?

看看方法解析顺序:

print(high.mro())

这会打印:

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

认为 super() 表示 "next in line",其中 line 是上面显示的 classes 的列表。因此,super(low1, self) 发现 low2 作为行中的下一个 class。