48

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's foo and store the result to tmp
    return "C"+tmp

What shall be written instead of ... so that the grandparent method foo in class A is called? I tried super().foo(), but it just calls parent method foo in class B.

I am using Python 3.

4

4 Answers 4

60

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
2

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.

2

You can simply be explicit about the class. super() allows you to be implicit about the parent, automatically resolving Method Resolution Order, but there's nothing else that's special about it.

class C(B):
    def foo(self):
       tmp = A.foo(self)
       return "C"+tmp
2
  • "Method Resolution Order" (MRO)
    – user1781434
    Mar 25, 2017 at 13:38
  • Thanks Tobias, fixed :)
    – Julien
    Mar 25, 2017 at 13:39
1

You can explicity call the method from the grandparent class:

class C(B):
    def foo(self):
       tmp = A.foo()
       return "C" + tmp
1
  • 1
    Thanks for the advice @UnholySheep. Please see the updated answer. Mar 25, 2017 at 13:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.