Python inheritance - how to name the grandparent method?

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):
    tmp = ... # call A foo and store the result to tmp
    return "C"+tmp

      

What should be written instead ...

in order to call the grandparent method foo

on a class A

? I tried super().foo()

it but it just calls the parent method foo

on the class B

.

I am using Python 3.

+3


source to share


4 answers


There are two ways to get around this:

Or you can explicitly use the A.foo (self) method as others have suggested - use this when you want to call a method of class A 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 foo and store the result to tmp
    return "C"+tmp

      



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

class C(B):
  def foo(self):
    tmp = super(B, self).foo() # call B father foo and store the result to tmp
    return "C"+tmp

      

+4


source


You can call the method call from the grandparent class:



class C(B):
    def foo(self):
       tmp = A.foo()
       return "C" + tmp

      

+1


source


You can just specify the class. super()

allows you to implicitly declare the parent, automatically allowing "Method Resolution Order" , but there is nothing special about that.

class C(B):
    def foo(self):
       tmp = A.foo(self)
       return "C"+tmp

      

+1


source


Calling the parent method of the parent that has been overridden by the parent This discussion has an explanation on how to return to the tree.

+1


source







All Articles