【问题标题】:Which one to use: super() or self.function() with function defined in the parent class使用哪一个:super() 或 self.function(),函数在父类中定义
【发布时间】:2021-01-14 10:30:22
【问题描述】:

让我们考虑以下虚拟示例:

class A:
    def __init__(self, a):
        self.a = a
        self.backup_a = a
        
    def reset_a(self):
        self.a = self.backup_a
        print ('Stop touching my stuff!')
        
class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
var = A(2)
var.reset_a()

var = B(2, 4)
var.f()

要向B 添加一个方法,该方法使用来自A 的方法reset_a,使用super().self. 的boh 语法有效。哪一个更正确,为什么?

class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
    def f(self):
        self.reset_a()

class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
    def f(self):
        super().reset_a()

【问题讨论】:

  • 这取决于,如果你正在调用一个你在新类中覆盖的函数,你使用super(),如果该函数没有被覆盖,你使用self
  • @xcodz-dot 这也是我的假设。谢谢。是的..错字..
  • 继承其超类的所有方法和属性。如果您明确需要调用父版本的方法,则只需要super(),就像您在__init__ 中所做的那样,否则会导致无限递归。

标签: python class inheritance super


【解决方案1】:

继承自动使父级的所有方法(“函数”)对子级可用。但是,如果孩子重新实现了一个方法,这会隐藏孩子的父方法。

  • 使用self.method 访问方法无论它是在子级还是父级中定义的。
  • 使用super().method显式跳过子定义的方法,而访问父方法。

一般来说,一个方法应该使用self.method来访问其他方法,但super().method来访问它自己的父定义。

这是因为在深度继承中,一个方法不能依赖于另一个方法是否/如何被覆盖——只有methods of well-behaved child classes are indistinguishable from methods of the parent class。一个方法只能可靠地知道它自己确实覆盖了它自己的父方法

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-23
    • 1970-01-01
    • 2013-11-25
    • 2017-05-09
    相关资源
    最近更新 更多