Multiple inheritance with a common base class

Duncan Booth duncan.booth at invalid.invalid
Tue Aug 10 08:38:22 EDT 2004


Markus Bertheau <twanger at bluetwanger.de> wrote in 
news:mailman.1439.1092140352.5135.python-list at python.org:

> It outputs:
> 
> CommonBase.no: 0
> CommonBase.no: 0
> 
> If there was only one copy of the common base class, I'd have expected
> an output similar to
> 
> CommonBase.no: 0
> CommonBase.no: 3
> 
> This renders multiple inheritance pretty useless for me.
> 
> Can someone clear this all up and tell me how multiple inheritance is
> supposed to work in python?

Well of course it outputs 0 twice. That's because after LeafA initialised  
CommonBase, and set its value to 3 you then reinitialised it from LeafB and 
set the value back to 0.

Do this instead:

class CommonBase:
    def __init__(self):
        self.no = 0
    def setNo(self, no):
        self.no = no
 
class LeafA(CommonBase):
    def __init__(self):
        super(LeafA, self).__init__()
        print("LeafA:CommonBase.no: %i" % self.no)
        CommonBase.setNo(self, 3)
 
class LeafB(CommonBase):
    def __init__(self):
        super(LeafB, self).__init__()
        print("LeafB:CommonBase.no: %i" % self.no)
        CommonBase.setNo(self, 4)
 
class Multi(LeafA, LeafB):
    def __init__(self):
        super(Multi, self).__init__()
 
m = Multi()

Which gives you the output:

LeafB:CommonBase.no: 0
LeafA:CommonBase.no: 4

Using super will ensure that you get a reliable chain of method calls. In 
this case it means that Multi.__init__ calls LeafA.__init__ which calls 
LeafB.__init__ which then calls CommonBase.__init__. Note that LeafA 
propogates the call to LeafB even though LeafA has no knowledge of the 
existence of LeafB.



More information about the Python-list mailing list