【问题标题】:Difference between super() and super (className,self) in Python [duplicate]Python中super()和super(className,self)之间的区别[重复]
【发布时间】:2019-06-07 08:03:21
【问题描述】:

我的代码被剪断了:

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 python-3.x class inheritance


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-11-15
    • 2014-05-10
    • 2019-02-20
    • 1970-01-01
    • 2018-02-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多