【问题标题】:multiple inheritance of pythonpython的多重继承
【发布时间】:2017-09-20 20:03:12
【问题描述】:

How does Python's super() work with multiple inheritance? 一个答案解释了这个例子的原因:

class First(object):
  def __init__(self):
    super(First, self).__init__()
    print "first"

class Second(object):
  def __init__(self):
    super(Second, self).__init__()
    print "second"

class Third(First, Second):
  def __init__(self):
    super(Third, self).__init__()
    print "that's it"

答案是:

>>> x = Third()
second
first
that's it

根据解释,是因为:

First__init__ 内部super(First, self).__init__() 调用Second__init__,因为这是MRO 规定的!

他是什么意思?为什么调用 First super __init__ 会调用 Second 的 __init__?我认为First与Second无关?

据说:“因为那是MRO规定的”,我看了https://www.python.org/download/releases/2.3/mro/ 但还是没有头绪。

谁能解释一下?

【问题讨论】:

  • 与名称相反,super 不是指超类。 First 或 Second 是否有任何关系并不重要。
  • 好的。我懂了。 super 表示遵循 MRO 指令。

标签: python multiple-inheritance method-resolution-order


【解决方案1】:

各个类的 MRO(方法解析顺序)是什么并不重要。唯一重要的是(如果您使用 super)是您调用该方法的类的 MRO。

所以当您调用Third.__init__ 时,它会跟随Third.mro,即Third, First, Second, object

>>> Third.mro()
[__main__.Third, __main__.First, __main__.Second, object]

因此,任何super 都会在 MRO 中查找下一个超类,而不是您“所在”的实际类的超类。

【讨论】:

  • 现在我明白了。太混乱了。
猜你喜欢
  • 2020-12-18
  • 2021-08-05
  • 1970-01-01
  • 2021-05-16
  • 2015-05-02
  • 1970-01-01
  • 2016-02-25
  • 2012-08-08
  • 2021-05-08
相关资源
最近更新 更多