conditional __init__

Chris Rebert clp2 at rebertia.com
Mon Nov 2 15:00:15 EST 2009


On Mon, Nov 2, 2009 at 12:40 PM, King <animator333 at gmail.com> 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?
>
> Is there a better/another way to do conditional initialization as
> needed above?

Which initializers are called *has no effect* on what order base
classes are consulted in when looking up methods. To change the lookup
order, you need to change the order of the base classes in the class
statement.

Your problem could be fixed by:

1. Changing the code so the initializers do have an effect through
what they initialize instance variables to;
class A(object):
   def __init__(self):
       self.name = "A"
   def printme(self):
       print "I am", self.name

class B(object):
   def __init__(self):
       self.name = "B"
   def printme(self):
       print "I am", self.name

2. Use a factory function to return an instance of the proper class:

class K1(A, B):
    pass

class K2(B, A):
    pass

def newK(value):
    if value == 0:
        return K1()
    elif value == 1:
        return K2()

Cheers,
Chris
--
http://blog.rebertia.com



More information about the Python-list mailing list