yingdong
yingdong

Reputation: 13

multiple inheritance execution order

code1:

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

code2:

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

the output of code1 is:

low2 test
low1 test

the output of code2 is:

low1 test

when I call why test method of a high object, it execute test method of both low1 and low2?

Upvotes: 1

Views: 536

Answers (1)

Mike Müller
Mike Müller

Reputation: 85482

Have a look at the method resolution order:

print(high.mro())

This prints:

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

Think of super() meaning "next in line", where line is the list of classes shown above. Therefore, super(low1, self) finds low2 as the class next in line.

Upvotes: 2

Related Questions