On 15/09/11 15:35, Chris Rebert wrote: > On Wed, Sep 14, 2011 at 10:20 PM, Matthew Pounsett > <[email protected]> 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
[email protected] | http://www.rfk.id.au/ramblings/gpg/ for details
signature.asc
Description: OpenPGP digital signature
-- http://mail.python.org/mailman/listinfo/python-list
