1

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?

Ulrich Eckhardt
  • 16,572
  • 3
  • 28
  • 55
yingdong
  • 13
  • 2
  • 1
    You called `super(low2...` in code1. If you are going to use `super` please [learn to understand how they work and why you might use them](http://stackoverflow.com/questions/576169/understanding-python-super-with-init-methods). – metatoaster Oct 30 '15 at 03:39
  • I just added the "Python 2" tag to the question. The reason is that the behaviour of inheritance and `super()` changed a bit between Python 2 and Python 3. BTW: If you're learning Python, don't start with Python 2 but use the current version 3 from the start, it offers quite a few advantages. – Ulrich Eckhardt Oct 30 '15 at 06:48

1 Answers1

2

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.

Mike Müller
  • 82,630
  • 20
  • 166
  • 161