cause __init__ to return a different class?

Ryan Kelly ryan at rfk.id.au
Thu Sep 15 01:54:06 EDT 2011


On 15/09/11 15:35, Chris Rebert wrote:
> On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett
> <matt.pounsett at gmail.com> 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:
> http://docs.python.org/reference/datamodel.html#object.__new__


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):

        @classmethod
        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 :-)


  Cheers,

    Ryan


-- 
Ryan Kelly
http://www.rfk.id.au  |  This message is digitally signed. Please visit
ryan at rfk.id.au        |  http://www.rfk.id.au/ramblings/gpg/ 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: <http://mail.python.org/pipermail/python-list/attachments/20110915/9d0fb44c/attachment-0001.sig>


More information about the Python-list mailing list