King wrote: > class A(object): > def __init__(self): > pass > def printme(self): > print "I am A" > > class B(object): > def __init__(self): > pass > def printme(self): > print "I am B" > > class K(A, B): > def __init__(self, value=0): > if value == 0: > A.__init__(self) > print "__init__ A" > elif value == 1: > B.__init__(self) > print "__init__ B" > self.printme() > > o = K(value=1) > > Output >>>__init__ B >>>I am A > > In above code "B" is correctly getting initialized as per condition. > How ever method "printme" is printing "I am A". > Instead it has to print "I am B" because "B" is the one that has been > initialized. What's wrong here?
It prints "I am A" because K inherits from A before B. Your __init__ methods don't do anything, so it doesn't matter which one you call. You seem to be thinking that running __init__ magically determines the class of the object, but it doesn't; it's just code that runs when the object is first created. When you do self.printme(), it decides to use A.printme because you did "class K(A, B)". If you do class K(B, A)" it will use B.printme. I imagine it's possible to do fiendish things and try to choose the superclass inheritance order at runtime, but you should be wary of this. In your example, why don't you just have K override printme and dispatch to A or B depending on "value"? -- --OKB (not okblacke) Brendan Barnwell "Do not follow where the path may lead. Go, instead, where there is no path, and leave a trail." --author unknown -- http://mail.python.org/mailman/listinfo/python-list