Python inheritance - how to call grandparent method?

后端 未结 2 1993
情深已故
情深已故 2021-02-11 19:12

Consider the following piece of code:

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

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

class C(B):
  def foo(self):
            


        
相关标签:
2条回答
  • 2021-02-11 19:53

    There are two ways to go around this:

    Either you can use A.foo(self) method explicitly as the others have suggested - use this when you want to call the method of the A class with disregard as to whether A is B's parent class or not:

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

    Or, if you want to use the .foo() method of B's parent class regardless of whether the parent class is A or not, then use:

    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
    
    0 讨论(0)
  • 2021-02-11 19:53

    Calling a parent's parent's method, which has been overridden by the parent There is an explanation in this discuss already on how to go back in the tree.

    0 讨论(0)
提交回复
热议问题