python - 使用多重继承时如何使用super来初始化所有父类

标签 python

How does Python's super() work with multiple inheritance?

我在看上面的问题/答案,把自己弄糊涂了

 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"

Fourth()
third
second
thats it

 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"

Fourth()
second
thats it

有人可以向我解释一下为什么顶部打印 "third" 而底部不打印的原因吗?

我觉得在幕后发生了某种我没有看到的秩序/顺序。

-- 四.mro

在Second中注释掉super
(, , , , )

super 第二
(, , , , )

最佳答案

super 实际上并不调用父类(super class)。它根据方法解析顺序 (MRO) 调用下一个方法。您的示例类的 MRO 看起来如下所示:

Fourth
Second
Third
First

也就是说,使用 Fourth 中的 super 可以得到 Second 上的方法。使用 Second 中的 super 可以获得 Third 上的方法。等

在第一个例子中:

  1. Fourth.__init__ 被调用。
  2. Fourth.__init__ 通过 super 调用 Second.__init__
  3. Second.__init__ 通过 super 调用 Third.__init__
  4. Third.__init__ 打印“third”
  5. Second.__init__ 打印“second”
  6. Fourth.__init__ 打印“就是这样”。

在第二个例子中:

  1. Fourth.__init__ 被调用。
  2. Fourth.__init__ 通过 super 调用 Second.__init__
  3. Second.__init__ 打印“second”
  4. Fourth.__init__ 打印“就是这样”。

所以,是的,更改 Second 中的 super 调用会改变是否调用 Third 上的某些内容,即使 Third 不是 Second 的父类(super class)。这确实令人费解。我推荐阅读 "Python's Super is nifty, but you can't use it" .这就是我读到的解释,上面的内容对我来说是有意义的。

关于python - 使用多重继承时如何使用super来初始化所有父类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19365574/

相关文章:

python - 有没有办法使 dis.dis() 递归打印代码对象?

java - 从java导入django模块

python - 使用 pandas 或 scikit-learn 对多维数组进行一次性编码

javascript - 如何将 jQuery 范围 slider 值获取到表单中以存储在 Django 的数据库中

python - 如何以 sudo 用户身份执行 pexpect spawn 命令?

python - 根据另一个列表中的元素进行列表划分

python - 查找数据区间并对其进行排序

Python文本提取

python - 跳出当前迭代的 for 循环

python - 使用 scrapy python 使用 post 请求加载更多文章