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

Mat*_*ieu 3 python inheritance class super

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

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

要添加一个方法,该方法使用fromB方法,boh 语法与or一起工作。哪一种更正确,为什么?reset_aAsuper().self.

class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
    def f(self):
        self.reset_a()
Run Code Online (Sandbox Code Playgroud)

或者

class B(A):
    def __init__(self, a, b):
        super().__init__(a)
        self.b = b
        
    def f(self):
        super().reset_a()
Run Code Online (Sandbox Code Playgroud)

Mis*_*agi 5

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

\n
    \n
  • 用于self.method访问方法,无论该方法是在子级还是父级中定义。
  • \n
  • 用于显super().method跳过子级定义的方法,并访问父级方法。
  • \n
\n

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

\n

这是因为在深度继承中,一个方法不能依赖于另一个方法是否/如何被覆盖\xe2\x80\x93,只有行为良好的子类的方法与父类的方法无法区分。方法只能可靠地知道它自己确实重写了自己的父方法。

\n