本文介绍了关于python MRO和如何super()行为的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我想知道如何 __ mro __ 和超级在python工作,我发现了一些有趣的东西,对我来说奇怪,因为我得到的东西,不是我在阅读 __ mro __ 后理解。这是代码段。

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.

代码段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()

输出:

 B to C

代码段2: 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()

输出:

B to A

然后现在我得到了我的预期。

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

推荐答案

D的MRO是[D,B,C,A,object ]。

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

super(C,self)〜A

super(B,self)〜C

不是关于 MyClass 的基类,而是关于 MyClass

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

如注释中所述, super(...)下一个类在MRO中,但委派给它的调用。

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

这篇关于关于python MRO和如何super()行为的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 08:37