在不覆盖方法的子类中调用 super().method()

Calling super().method() in a subclass that does not override method

superPython documentation 状态:

This is useful for accessing inherited methods that have been overridden in a class.

覆盖method的子类中调用super().method()是否有意义?

对我来说没有,因为调用 self.method() 是等效的,也就是说继承会在 self 的超类中使用相同的 [=18] 查找 method =] 方法解析顺序(由 self 的超类层次结构的 C3 linearization 给出)比 super.

所以对我来说,super 在这种情况下很有用:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def f(self):
        super().f()
        print("C")

C().f()  # prints A C

但不在这一个中:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        super().f()  # should be just self.f()
        print("C")

C().g()  # prints A C

如@chepner 所述,在不覆盖 method 的子类中调用 super().method() 等同于调用 self.method()。差异出现在覆盖 method.

的子类的子类中

比较:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        super().f()  # == super(C, self).f(), so lookup starts after C in type(self).__mro__
        print("C")

class D(C):    
    def f(self):
        print("D")

D().g()  # prints A C, since D.__mro__ == (D, C, B, A, object)

与:

class A:
    def f(self):
        print("A")

class B:
    pass

class C(B, A):
    def g(self):
        self.f()  # lookup starts at the beginning in type(self).__mro__
        print("C")

class D(C):
    def f(self):
        print("D")

D().g()  # prints D C, since D.__mro__ == (D, C, B, A, object)