Multiple inheritance with a common base class
Peter Otten
__peter__ at web.de
Tue Aug 10 08:38:42 EDT 2004
Markus Bertheau wrote:
> ? ???, 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:
>
> class CommonBase:
> def __init__(self):
> self.no = 0
> def setNo(self, no):
> self.no = no
>
> class LeafA(CommonBase):
> def __init__(self):
> CommonBase.__init__(self)
> print("CommonBase.no: %i" % self.no)
> CommonBase.setNo(self, 3)
>
> class LeafB(CommonBase):
> def __init__(self):
> CommonBase.__init__(self)
> print("CommonBase.no: %i" % self.no)
> CommonBase.setNo(self, 4)
>
> class Multi(LeafA, LeafB):
> def __init__(self):
> LeafA.__init__(self)
insert
print self.no
to verify that at this point self.no is indeed 3. LeafB.__init__() then
calls CommonBase.__init__() which in turn sets self.no to 0 again.
> LeafB.__init__(self)
>
> m = Multi()
>
> 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?
Remember that __init__() is just a method like any other that will be called
automaticallly after the instance is created - not a constructor. If you
call it explicitly it will be executed no matter where you are in your
program. If you want to ensure that all methods with the same name are
executed once across an inheritance hierarchy, have a look at super().
If you know some C++ it might help to regard all python base classes as
virtual.
http://www.python.org/2.2.2/descrintro.html
http://www.python.org/2.3/mro.html
might also interest you - as a bonus, the latter has some nice ascii-art :-)
Peter
More information about the Python-list
mailing list