gpt4 book ai didi

python - 'super' 在 Python 中做什么? - super().__init__() 和显式父类(super class) __init__() 的区别

转载 作者:IT老高 更新时间:2023-10-28 12:01:58 28 4
gpt4 key购买 nike

有什么区别:

class Child(SomeBaseClass):
def __init__(self):
super(Child, self).__init__()

和:
class Child(SomeBaseClass):
def __init__(self):
SomeBaseClass.__init__(self)

我见过 super在只有单一继承的类中被大量使用。我可以理解为什么你会在多重继承中使用它,但不清楚在这种情况下使用它的好处是什么。

最佳答案

super()的好处在单一继承中是最小的——大多数情况下,您不必将基类的名称硬编码到使用其父方法的每个方法中。

但是,如果没有 super(),几乎不可能使用多重继承。 .这包括常见的习惯用法,如混入、接口(interface)、抽象类等。这会扩展到以后扩展您的代码的代码。如果有人后来想写一个扩展 Child 的类和 mixin,他们的代码将无法正常工作。

关于python - 'super' 在 Python 中做什么? - super().__init__() 和显式父类(super class) __init__() 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/222877/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com