How do I say "two classes up in the inheritance chain" in python?

Bruno Desthuilliers bruno.42.desthuilliers at websiteburo.invalid
Tue Jan 27 10:14:38 CET 2009

Daniel Fetchinson a écrit :
> I have two classes that both inherit from two other classes which both
> inherit from a single class. The two children have two almost
> identical methods:
> class grandparent( object ):
>     def meth( self ):
>         # do something
> class parent1( grandparent ):
>     def meth( self ):
>         # do something p1
>         super( parent1, self ).meth( )
> class parent2( grandparent ):
>     def meth( self ):
>         # do something p2
>         super( parent2, self ).meth( )
> class child1( parent1 ):
>     def meth( self ):
>         # do something c
>         super( parent1, self ).meth( ) # I want to invoke meth on grandparent

If so, it might be better to explicitly call grandparent.meth (passing 
self as first argument). But this is an obvious design smell IMHO. What 
you have is :

def meth(self):

Looks like a candidate for a template method. Since you don't have hand 
on Grandparent, the simplest would be to add an additional base class, ie:

class Abstract(Grandparent):
     def do_something(self):
         raise NotImplementedError

     def meth(self):
         super(Abstract, self).meth()

class Parent1(Abstract):
     def do_something(self):
        # do something p1

class Parent2(Abstract):
     def do_something(self):
        # do something p2

Now you're problem is to factor out do_something() for Child1 and 
Child2. The solution is quite simple : just define it outside the class 
statements, and adds it afterward:

def do_something_children(self):
    # code here

class Child1(Parent1):
     # code here

Child1.do_something = do_something_children

class Child2(Parent2):
     # code here

Child2.do_something = do_something_children


More information about the Python-list mailing list