cause __init__ to return a different class?

Matthew Pounsett matt.pounsett at gmail.com
Thu Sep 15 01:20:19 EDT 2011


I'm wondering if there's a way in python to cause __init__ to return a class other than the one initially specified.  My use case is that I'd like to have a superclass that's capable of generating an instance of a random subclass.  

I've tried both returning the subclass (as I would when overloading an operator) but I get the complaint that __init__ wants to return None instead of a type.

The other thing I tried was overwriting 'self' while inside __init__ but that doesn't seem to work either.

class Parent(object):
    def __init__(self, foo):
        if foo == True:
            self = Child(foo)

class Child(Parent):
    def __init__(self, foo):
        pass

Is there a way to do this?  



More information about the Python-list mailing list