Python继承 - 如何调用grandparent方法?

kar*_*sss 14 python

考虑以下代码:

class A:
  def foo(self):
    return "A"

class B(A):
  def foo(self):
    return "B"

class C(B):
  def foo(self):
    tmp = ... # call A's foo and store the result to tmp
    return "C"+tmp
Run Code Online (Sandbox Code Playgroud)

应该写什么来代替课堂上...的祖父母方法呢?我试过,但它只是在课堂上调用父方法.fooAsuper().foo()fooB

我正在使用Python 3.

Ale*_*ssa 15

有两种方法可以解决这个问题:

您可以像其他人建议的那样明确使用A.foo(self)方法 - 当您想要调用A类的方法而忽略A是否是B的父类时使用它:

class C(B):
  def foo(self):
    tmp = A.foo(self) # call A's foo and store the result to tmp
    return "C"+tmp
Run Code Online (Sandbox Code Playgroud)

或者,如果要使用B的父类的.foo()方法,无论父类是否为A,则使用:

class C(B):
  def foo(self):
    tmp = super(B, self).foo() # call B's father's foo and store the result to tmp
    return "C"+tmp
Run Code Online (Sandbox Code Playgroud)