cause __init__ to return a different class?

Ryan Kelly ryan at
Thu Sep 15 07:54:06 CEST 2011

On 15/09/11 15:35, Chris Rebert wrote:
> On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett
> <matt.pounsett at> 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.
> <snip>
>> Is there a way to do this?
> Override __new__() instead:

The above will do exactly what you want, but it's generally bad style
unless you have a very specific use-case.  Is there a particular reason
you need to "magically" return a subclass, rather than making this
explicit in the code?

To be friendlier to others reading your code, I would consider using a
classmethod to create an alternative constructor:

   class MyBaseClass(object):

        def get_random_subclass(cls, *args, **kwds)
            subcls = random.choice(cls.__subclasses__())
            return subcls(*args, **kwds)

To me, this reads pretty cleanly and makes it obvious that something
unusual is going on:

    obj = MyBaseClass.get_random_subclass()

While this hides the intention of the code and would require additional
documentation or comments:

    obj = MyBaseClass()  # note: actually returns a subclass!

Just a thought :-)



Ryan Kelly  |  This message is digitally signed. Please visit
ryan at        | for details

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 262 bytes
Desc: OpenPGP digital signature
URL: <>

More information about the Python-list mailing list