Multiple inheritance with a common base class

Heiko Wundram heikowu at ceosg.de
Tue Aug 10 08:34:39 EDT 2004


Am Dienstag, 10. August 2004 14:19 schrieb Markus Bertheau:
> В Втр, 10.08.2004, в 13:37, Markus Bertheau пишет:
>
> Also I observe that the instance will in fact _not_ have a single copy
> of the data attributes used by the common base class. The following
> example demonstrates this:

No, this example doesn't demonstrate this, rather, you can't read your code 
correctly... ;-) Let's look at the oder at which the commands are executed.

class Multi(LeafA, LeafB):
    def __init__(self):
        LeafA.__init__(self)

---> Call into LeafA.__init__...

class LeafA(CommonBase):
    def __init__(self):
        CommonBase.__init__(self)

---> Call into CommonBase.__init__

class CommonBase:
    def __init__(self):
        self.no = 0

---> Set self.no to zero.

        print("CommonBase.no: %i" % self.no)

---> Print self.no (zero)

        CommonBase.setNo(self, 3)

---> Call into CommonBase.setNo

class CommonBase:
    def setNo(self, no):
        self.no = no

---> Set self.no to three.

        LeafB.__init__(self)

---> Call into LeafB.__init__

class LeafB(CommonBase):
    def __init__(self):
        CommonBase.__init__(self)

---> Call into CommonBase.__init__

class CommonBase:
    def __init__(self):
        self.no = 0

---> (Re)set self.no to zero.

        print("CommonBase.no: %i" % self.no)

---> Print self.no (zero)

        CommonBase.setNo(self, 4)

---> Call into CommonBase.setNo

class CommonBase:
    def setNo(self, no):
        self.no = no

---> Set self.no to four

Does this explain what is happening, and why multiple inheritence doesn't work 
as you expect it to (rather, you have to be real careful about it?).

Heiko.



More information about the Python-list mailing list