Question

Today i was trying to figure out how __mro__ and super works in python, I found something interesting as well as strange to me, because I got something which is not that i understood after reading __mro__. Here is the code snippets.

Code Snippets 1:

#!/usr/bin/pyhon

class A(object):
    def test(self):
        return 'A'

class B(A):
    def test(self):
        return 'B to %s' % super(B, self).test()

class C(A):
    def test(self):
        return 'C'

class D(B, C):
    pass

print D().test()

Output :

 B to C

Code snippet 2: When I update my super inside class B:

#!/usr/bin/pyhon

class A(object):
    def test(self):
        return 'A'

class B(A):
    def test(self):
        return 'B to %s' % super(C, self).test()

class C(A):
    def test(self):
        return 'C'

class D(B, C):
    pass

print D().test()

Output:

B to A

Then now i got what I expected before. Could someone please explain how mro works with super ?

Was it helpful?

Solution

The MRO for D is [D, B, C, A, object].

super(C, self) ~ A

super(B, self) ~ C

super(MyClass, self) is not about the "base class of MyClass", but about the next class in the MRO list of MyClass.

As stated in the comments, super(…) actually does not return the next class in the MRO, but delegates calls to it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top