我有像这样截取的代码:
class A:
def test(self):
return 'A'
class B(A):
def test(self):
return 'B->' + super(B, self).test()
print(B().test())
输出 : B->A
如果我写这样的东西,那么我会得到相同的输出:
class A:
def test(self):
return 'A'
class B(A):
def test(self):
return 'B->' + super().test() # change to super()
print(B().test())
在这两种情况下,我都得到了相同的输出。那么,我想知道这两种类型的super
调用有什么区别?使用它们中的任何一个的优缺点是什么?
在 Python 2 中,只有super(className,self)
语法是可能的。由于它是最常用的版本,截至Python 3
,不提供任何参数将起到相同的作用。
超级有两个典型的用例。在具有单一继承的类层次结构中,super 可用于引用父类而无需显式命名它们,从而使代码更易于维护