Python 为什么要使用super()而不是uuu init_uuuu()?
如果我们有类Python 为什么要使用super()而不是uuu init_uuuu()?,python,class,multiple-inheritance,superclass,Python,Class,Multiple Inheritance,Superclass,如果我们有类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)
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.\uuuu init\uuuuuuuuuuself,x)
比super()更好。\uuuuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuux)
因为它支持多重继承(而我没有找到使用super()
的方法):
在上一个示例中尝试使用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()。\uuuu init\uuu()
,Python将自动按正确的顺序调用基类的所有构造函数(在第二个示例中,首先是A
,然后是B
构造函数)
这是Python的优点之一,它可以很好地处理多重继承:)。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