What does #39;super#39; do in Python? - difference between super().__init__() and explicit superclass __init__()(“超级在 Python 中做了什么?- super().__init__() 和显式超类 __init__() 之间的区别)
问题描述
两者有什么区别:
class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()
和:
class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)
我已经看到 super
在只有单一继承的类中被大量使用.我可以理解您为什么要在多重继承中使用它,但不清楚在这种情况下使用它有什么优势.
I've seen super
being used quite a lot in classes with only single inheritance. I can see why you'd use it in multiple inheritance but am unclear as to what the advantages are of using it in this kind of situation.
推荐答案
super()
在单继承中的好处是微乎其微的——大多数情况下,您不必对将基类的名称添加到使用其父方法的每个方法中.
The benefits of super()
in single-inheritance are minimal -- mostly, you don't have to hard-code the name of the base class into every method that uses its parent methods.
但是,如果没有 super()
,几乎不可能使用多重继承.这包括常见的习惯用法,如 mixins、接口、抽象类等.这会扩展到以后扩展您的代码.如果后来有人想编写一个扩展 Child
和 mixin 的类,他们的代码将无法正常工作.
However, it's almost impossible to use multiple-inheritance without super()
. This includes common idioms like mixins, interfaces, abstract classes, etc. This extends to code that later extends yours. If somebody later wanted to write a class that extended Child
and a mixin, their code would not work properly.
这篇关于“超级"在 Python 中做了什么?- super().__init__() 和显式超类 __init__() 之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:“超级"在 Python 中做了什么?- super().__init__() 和显式超类 __init__() 之间的区别


基础教程推荐
- 哪些 Python 包提供独立的事件系统? 2022-01-01
- 使用Python匹配Stata加权xtil命令的确定方法? 2022-01-01
- 合并具有多索引的两个数据帧 2022-01-01
- 如何在 Python 中检测文件是否为二进制(非文本)文 2022-01-01
- 如何在Python中绘制多元函数? 2022-01-01
- 使用 Google App Engine (Python) 将文件上传到 Google Cloud Storage 2022-01-01
- 使 Python 脚本在 Windows 上运行而不指定“.py";延期 2022-01-01
- Python 的 List 是如何实现的? 2022-01-01
- 将 YAML 文件转换为 python dict 2022-01-01
- 症状类型错误:无法确定关系的真值 2022-01-01