如何在使用多重继承时使用super初始化所有父项

eal*_*eon 6 python

Python的super()如何与多重继承一起工作?

我正在看上面的问题/答案,让自己很困惑

 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

超级秒
(,,, )

Cla*_*diu 5

super实际上没有调用超类。它根据方法解析顺序(MRO)调用下一个方法。您的示例类的MRO如下所示:

Fourth
Second
Third
First
Run Code Online (Sandbox Code Playgroud)

也就是说,使用superfrom为Fourth您提供了方法Second。使用superfrom为Second您提供一种方法Third。等等

在第一个示例中:

  1. Fourth.__init__ 叫做。
  2. Fourth.__init__Second.__init__通过致电super
  3. Second.__init__Third.__init__通过致电super
  4. Third.__init__ 打印“第三”
  5. Second.__init__ 打印“第二”
  6. Fourth.__init__ 打印“就是这样”。

在第二个示例中:

  1. Fourth.__init__ 叫做。
  2. Fourth.__init__Second.__init__通过致电super
  3. Second.__init__ 打印“第二”
  4. Fourth.__init__ 打印“就是这样”。

因此,是的,即使不是的超类,更改superin中的调用Second也会更改是否调用了on 。这确实令人困惑。我建议阅读“ Python的Super很漂亮,但您不能使用它”。这就是我读到的解释,它对我来说有意义。ThirdThirdSecond

  • 另一篇相关文章:[Python的super()被认为是超级!](http://rhettinger.wordpress.com/2011/05/26/super-considered-super/) (2认同)