Instantiating a class from its name

Emile van Sebille emile at fenx.com
Sat Nov 17 22:45:56 CET 2001


"Daniel Klein" <danielk at aracnet.com> wrote in message
news:sgidvt8e5l5m7jmlk0grkqs9pm66beja8k at 4ax.com...
> I need to create a class factory such that passing the 'name' of the class
to the method will
> produce an instance of that class. In Java, you do this with
>
> Class c = Class.forName("name_of_class");
> MyClass m = c.newInstance();
>
> What is the Python equivalent?
>

>>> class A:pass
...
>>> a = locals()['A']()
>>> a
<__main__.A instance at 007E5FE4>
>>> class C:
...     def __init__(self, val):
...             self.val = val
...
>>> c = locals()['C'](123)
>>> c.val
123
>>>

There's probably a better way, so by posting this I expect we'll find out.
;-)


--

Emile van Sebille
emile at fenx.com

---------




More information about the Python-list mailing list