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

Daniel Fetchinson fetchinson at googlemail.com
Tue Jan 27 02:51:37 EST 2009


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

class child2( parent2 ):
    def meth( self ):
        # do something c
        super( parent2, self ).meth( ) # I want to invoke meth on grandparent

The meth methods in child1 and child2 are the same, except that in the
last super call, one is referring to parent1, the other is referring
to parent2. If they were exactly the same I could use a mixin where I
could define this method, and both child1 and child2 would inherit
from this mixin too. In this way I wouldn't have to code these methods
twice. But how do I write this mixin? It needs to refer to the
grandparent in such a way that it works in both child1 and child2 and
bypasses both parent1 and parent2. How would I do that?

Notes: (1) of course child1 and child2 have all sorts of methods which
are different, only meth is almost the same. (2) I can't modify the
grandfather class.

Cheers,
Daniel

-- 
Psss, psss, put it down! - http://www.cafepress.com/putitdown



More information about the Python-list mailing list