我正在看上面的问题/答案,让自己很困惑
53 class First(object):
54 def __init__(self):
55 print "first"
56
57 class Second(First):
58 def __init__(self):
59 super(Second, self).__init__()
60 print "second"
61
62 class Third(First):
63 def __init__(self):
64 print "third"
65
66 class Fourth(Second, Third):
67 def __init__(self):
68 super(Fourth, self).__init__()
69 print "thats it"
Run Code Online (Sandbox Code Playgroud)
第四()
第三
秒
就是这样
53 class First(object):
54 def __init__(self):
55 print "first"
56
57 class Second(First):
58 def __init__(self):
59 #super(Second, self).__init__() <---- commented out
60 print "second"
61
62 class Third(First):
63 def __init__(self):
64 print "third"
65
66 class Fourth(Second, Third):
67 def __init__(self):
68 super(Fourth, self).__init__()
69 print "thats it"
Run Code Online (Sandbox Code Playgroud)
第四()
秒
就是这样
有人可以向我解释一下幕后发生的事情,为什么顶部印刷品"third"和底部印刷品没有?
我觉得在我看不到的场景背后会发生某种顺序/顺序.
- 第四.MRO
在第二个
(,,,,)中注释掉了super
超级秒
(,,, )
super实际上没有调用超类。它根据方法解析顺序(MRO)调用下一个方法。您的示例类的MRO如下所示:
Fourth
Second
Third
First
Run Code Online (Sandbox Code Playgroud)
也就是说,使用superfrom为Fourth您提供了方法Second。使用superfrom为Second您提供一种方法Third。等等
在第一个示例中:
Fourth.__init__ 叫做。Fourth.__init__Second.__init__通过致电super。Second.__init__Third.__init__通过致电super。Third.__init__ 打印“第三”Second.__init__ 打印“第二”Fourth.__init__ 打印“就是这样”。在第二个示例中:
Fourth.__init__ 叫做。Fourth.__init__Second.__init__通过致电super。Second.__init__ 打印“第二”Fourth.__init__ 打印“就是这样”。因此,是的,即使不是的超类,更改superin中的调用Second也会更改是否调用了on 。这确实令人困惑。我建议阅读“ Python的Super很漂亮,但您不能使用它”。这就是我读到的解释,它对我来说有意义。ThirdThirdSecond
| 归档时间: |
|
| 查看次数: |
139 次 |
| 最近记录: |