cause __init__ to return a different class?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Sep 15 08:00:26 CEST 2011


On Thu, 15 Sep 2011 03:20 pm Matthew Pounsett wrote:

> 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.


You need to override the constructor, not the initializer. By the time
__init__ is called, the instance has already been created.


> 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.

No, because self is just an ordinary local variable. Overwriting self just
changes the local variable, not the instance.

However, you can sometimes modify the instance's class. One sometimes useful
trick is something like this:


class Test(object):
    def __init__(self):
        if condition():
            self.__class__ = AnotherClass

which will work, and is supported, so long as Test class and AnotherClass
are compatible. (If they're not compatible, you'll get an exception.)



-- 
Steven




More information about the Python-list mailing list