Regarding python MRO and how super() behaves

大兔子大兔子 提交于 2019-12-10 11:54:05

问题


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 ?


回答1:


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.



来源:https://stackoverflow.com/questions/20545791/regarding-python-mro-and-how-super-behaves

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!