问题描述
有什么区别:
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中做了什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!