【发布时间】:2013-12-12 14:10:06
【问题描述】:
今天我试图弄清楚 __mro__ 和 super 在 python 中是如何工作的,我发现了一些对我来说既有趣又奇怪的东西,因为我得到了一些我在阅读 __mro__ 后并不理解的东西。这是代码sn-ps。
代码片段 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
代码 sn-p 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
然后现在我得到了我之前的预期。有人可以解释一下 mro 如何与 super 一起工作吗?
【问题讨论】:
-
我可以发誓一个很好的解释已经是 StackOverflow 搜索“Python super”的第一名,但显然不是。他们都没有真正解释它;最好的结果只是链接到其他网站。
-
是的,我什至试图从堆栈中的各种超级博客以及谷歌中找出答案。
-
-
感谢您的链接,这让我了解了很多我以前不知道的东西:)
标签: python class python-2.7 super method-resolution-order