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?

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. Commented Oct 30, 2015 at 3: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. Commented Oct 30, 2015 at 6:48

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.