[Python-Dev] Error in Python Tutorial on Multiple Inheritence (original) (raw)

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