代码之家  ›  专栏  ›  技术社区  ›  Mathieu

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

  •  0
  • Mathieu  · 技术社区  · 4 年前

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

    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 使用该方法 reset_a A ,boh语法 super(). self. 作品。哪一个更正确,为什么?

    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()
    
    0 回复  |  直到 4 年前
        1
  •  4
  •   MisterMiyagi    4 年前

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

    • 使用 self.method 访问方法 不管 无论是在孩子身上还是在父母身上定义的。
    • 使用 super().method 明确跳过 由子方法定义的方法,并访问父方法。

    一般来说,一种方法应该使用 自我方法 访问 其他 方法,但 super()方法 访问 自己的 父定义。

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