Python中super()和super(className,self)的区别

Tao*_*lam 4 python inheritance class python-3.x

我有代码剪断如下:

class A:
    def test(self):
        return 'A'

class B(A):
    def test(self):
        return 'B->' + super(B, self).test()

print(B().test())
Run Code Online (Sandbox Code Playgroud)

输出: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())
Run Code Online (Sandbox Code Playgroud)

在这两种情况下,我都得到相同的输出。那么,我想知道这两种调用的区别是super什么?使用它们中的任何一个都有什么优点和缺点?

Fre*_*ord 7

在 Python 2 中,只有super(className,self)语法是可能的。由于它是最常用的版本,因此不Python 3提供任何参数将起到相同的作用。

super 有两个典型的用例。在单继承的类层次结构中,可以使用 super 来引用父类而不显式命名它们,从而使代码更易于维护