使用哪一个:super() 或 self.function() 以及在父 class 中定义的函数

Which one to use: super() or self.function() with function defined in the parent class

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

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()

继承自动使 parent 的所有方法(“函数”)可用于 child。但是,如果 child re-implements 一个方法,这将隐藏 child.

的 parent 方法
  • 使用self.method访问方法不管它是否在child或parent中定义。
  • 使用super().method 显式跳过 child 定义的方法,而是访问parent 方法。

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

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