calling subclass constructor question

Steven Bethard steven.bethard at gmail.com
Sun Jun 19 19:33:28 EDT 2005


In Han Kang wrote:
> Anyway, I was wondering...I have an super class which is the superclass 
> for 5 other classes.  However, I want to be able to call the subclass 
> constructors from the super class.  Is this possible?

Are you trying to use your superclass as a factory?

If so, one option is something like:

py> class A(object):
...     @staticmethod
...     def subclass(i):
...         return A.__subclasses__()[i]()
...
py> class B(A):
...     pass
...
py> class C(A):
...     pass
...
py> A()
<__main__.A object at 0x011861B0>
py> A.subclass(0)
<__main__.B object at 0x01186070>
py> A.subclass(1)
<__main__.C object at 0x011861B0>

I've never used this strategy, but I know that others have.  You can 
probably search the list for __subclasses__ and find some more information.

STeVe



More information about the Python-list mailing list