Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python inheritance - how to call grandparent method?

Tags:

python

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.

like image 828
karlosss Avatar asked Mar 25 '17 13:03

karlosss


People also ask

Can you call a grandparent method in Java?

In Java, a class cannot directly access the grandparent's members. It is allowed in C++ though. In C++, we can use scope resolution operator (::) to access any ancestor's member in the inheritance hierarchy. In Java, we can access grandparent's members only through the parent class.


2 Answers

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 
like image 59
Alexander Rossa Avatar answered Oct 01 '22 09:10

Alexander Rossa


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.

like image 38
Zed Evans Avatar answered Oct 01 '22 10:10

Zed Evans