Python pattern for dropping the "grandparent" class implementation

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 template in python for sound MuteAnimal

to reference its grandparent class implementation Thing

? (eg super(MuteAnimal,self).super(Animal.self).sound()

?) Or is it better to use Mixin here?

+2


source to share


2 answers


As Alexander Rossa said in Python inheritance - how to call grandfather's method? :



There are two ways to get around this:

Alternatively, you can explicitly use the A.foo (self) method as others have suggested - use it when you want to call a method of class A, regardless of whether A is the parent of B 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 the parent class B regardless of 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

      

0


source


Is it wise to do this?

In MuteAnimal.sound

callsuper(Animal, self).sound()



because Animal is actually the parent class MuteAnimal ...

-1


source







All Articles