[Python-Dev] Error in Python Tutorial on Multiple Inheritence
Nick Coghlan
ncoghlan at iinet.net.au
Thu Aug 12 08:49:11 CEST 2004
Steven Kah Hien Wong wrote:
> Maybe I have misread, but I have interpreted that as meaning the two
> children will share the same instance of the base class. So if one child
> changes its parent, the other child will pick up that change, too.
This interpretation seems correct to me.
> But I did some quick tests, and it turns out this isn't so.
It *is* so if you actually change the common parent, rather than one of
the siblings (see modified example below).
In your original example, the new 'x' was stored inside ChildOne's class
dictionary, and so ChildTwo was not affected. To see the effect of the
shared parent, you need to actually change the value of 'x' that is
stored in CommonBase (as happens in the example below).
=====================
class CommonBase:
x = 0
class ChildOne(CommonBase):
def foo(self): CommonBase.x = 1 ##### Change here
class ChildTwo(CommonBase):
pass
class ChildOneAndTwo(ChildOne, ChildTwo):
def run(self):
ChildOne.foo(self) ##### Change Here
print "one =", ChildOne.x
print "two =", ChildTwo.x
ChildOneAndTwo().run()
=====================
Output is now:
$ python multi.py
one = 1
two = 1
=====================
In relation to Martin's post, the text is really talking about a problem
with 'instance' variables in the presence of multiple inheritance:
=====================
class Base(object):
def __init__(self):
super(Base, self).__init__()
self.x = 0
print "Base initialised"
def run(self): print "I am", self.x
class One(Base):
def __init__(self):
super(One, self).__init__()
self.x = 1
print "One initialised"
class Two(Base):
def __init__(self):
super(Two, self).__init__()
self.x = 2
print "Two initialised"
class OneTwo(One, Two):
def __init__(self):
super(OneTwo, self).__init__()
OneTwo().run()
=====================
Output is:
Base initialised
Two initialised
One initialised
I am 1
=====================
--
Nick Coghlan | Eugene, Oregon
Email: ncoghlan at email.com | USA
More information about the Python-Dev
mailing list