2
class Thing(object):
  def sound(self):
    return '' #Silent

class Animal(Thing):
  def sound(self):
    return 'Roar!'

class MuteAnimal(Animal):
   def sound(self):
    return '' #Silent

Is there a pattern in python for MuteAnimal's sound to refer to its grandparent class Thing's implementation? (eg super(MuteAnimal,self).super(Animal.self).sound() ?) Or is Mixin a better use case here?

user1008636
  • 2,989
  • 11
  • 31
  • 45
  • 2
    If a class needs direct access to overridden grandparent methods, you have a design problem. – user2357112 Mar 21 '17 at 20:05
  • How would you redesign this ? – user1008636 Mar 21 '17 at 20:06
  • Why does `Thing` automatically sound silent? – juanpa.arrivillaga Mar 21 '17 at 20:06
  • It's hard to say how to redesign a toy example like this, because initial questions like "why is there even a MuteAnimal class at all" and "why do Animals sound like "Roar!" by default" and "why is muteness modeled by a subclass" don't have much of an answer. – user2357112 Mar 21 '17 at 20:13
  • In this way calling a `MuteAnimal_obj.sound()` would return `' '`, so I suppose you could create another method, for example `def sound1(self): return Thing.sound(self)` that when called would also return also `' '` – coder Mar 21 '17 at 20:22

2 Answers2

0

As said by Alexander Rossa in Python inheritance - how to call grandparent method? :

There are two ways to go around this:

Either you can use explicitly A.foo(self) method 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 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
Antonin G.
  • 374
  • 2
  • 8
  • Also can overload a method in parent, which calls his parent, then call this method from grandchild. For overloading a function in python, which is not supported directly, take a look at this link: https://stackoverflow.com/questions/6434482/python-function-overloading – Reza Akraminejad Nov 02 '22 at 19:36
-1

Is it sensible to do this?

In MuteAnimal.sound, call super(Animal, self).sound()

because Animal is in fact, gradparent class of MuteAnimal...

madvn
  • 33
  • 7