Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling a parent's parent's method, which has been overridden by the parent

How do you call a method more than one class up the inheritance chain if it's been overridden by another class along the way?

class Grandfather(object):     def __init__(self):         pass      def do_thing(self):         # stuff  class Father(Grandfather):     def __init__(self):         super(Father, self).__init__()      def do_thing(self):         # stuff different than Grandfather stuff  class Son(Father):     def __init__(self):         super(Son, self).__init__()      def do_thing(self):         # how to be like Grandfather? 
like image 360
cosmo_kramer Avatar asked Aug 08 '13 04:08

cosmo_kramer


People also ask

How do you call a parent overridden method?

Invoking overridden method from sub-class : We can call parent class method in overriding method using super keyword. Overriding and constructor : We can not override constructor as parent and child class can never have constructor with same name(Constructor name must always be same as Class name).

How do you call a method overridden in Python?

In Python method overriding occurs by simply defining in the child class a method with the same name of a method in the parent class. When you define a method in the object you make this latter able to satisfy that method call, so the implementations of its ancestors do not come in play.

How do you call a parent call method in child class?

If you override a parent method in its child, child objects will always use the overridden version. But; you can use the keyword super to call the parent method, inside the body of the child method.


1 Answers

If you always want Grandfather#do_thing, regardless of whether Grandfather is Father's immediate superclass then you can explicitly invoke Grandfather#do_thing on the Son self object:

class Son(Father):     # ... snip ...     def do_thing(self):         Grandfather.do_thing(self) 

On the other hand, if you want to invoke the do_thing method of Father's superclass, regardless of whether it is Grandfather you should use super (as in Thierry's answer):

class Son(Father):     # ... snip ...     def do_thing(self):         super(Father, self).do_thing() 
like image 108
Sean Vieira Avatar answered Oct 09 '22 15:10

Sean Vieira