【问题标题】:Why use super() instead of __init__()?为什么使用 super() 而不是 __init__()?
【发布时间】:2015-01-09 11:04:44
【问题描述】:

如果我们有类A,定义如下,

class A:
    def __init__(self, x):
        self.x = x

为什么大多数人使用

class B(A):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

而不是

class B(A):
    def __init__(self, x, y):
        A.__init__(self, x)
        self.y = y

?我认为A.__init__(self, x)super().__init__(x) 更好,因为它支持多重继承(我没有找到使用super() 的方法):

class A:
    def __init__(self, x):
        self.x = x
class B:
    def __init__(self, y):
        self.y = y
class C(A, B):
    def __init__(self, x, y, z):
        A.__init__(self, x)
        B.__init__(self, y)
        self.z = z

当我尝试在前面的示例中使用super() 时,如下所示:

class A:
    def __init__(self, x):
        self.x = x
class B:
    def __init__(self, y):
        self.y = y
class C(A, B):
    def __init__(self, x, y, z):
        super().__init__(self, x)
        super().__init__(self, y)
        self.z = z

C 没有属性y(尝试:c = C(1, 2, 3)print(c.y) 在下一行)。

我做错了什么?

【问题讨论】:

  • super 正好用于多重继承,因此您不必在所有单独的超类上显式调用该方法。

标签: python class multiple-inheritance superclass


【解决方案1】:

如果你使用super().__init__(),Python 会自动以正确的顺序自行调用基类的所有构造函数(在你的第二个示例中,首先是A,然后是Bconstructors)。

这是 Python 的一大优点,它很好地处理了多重继承 :)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-30
    • 2021-11-26
    • 1970-01-01
    • 2020-07-30
    • 1970-01-01
    • 2013-11-01
    相关资源
    最近更新 更多