Instantiating a class from its name

Chris Tavares christophertavares at earthlink.net
Sun Nov 18 01:54:24 EST 2001


"Emile van Sebille" <emile at fenx.com> wrote in message
news:9t6m56$n4ld$1 at ID-11957.news.dfncis.de...
>
> "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.
> ;-)
>
>
> --

Since a class object is a python expression, you can use eval in this case
and be a little less confusing:

>>> class A: pass
...
>>> A
<class __main__.A at 007E2174>
>>> eval("A")
<class __main__.A at 007E2174>
>>> klass = eval("A")
>>> klass()
<__main__.A instance at 007E5E0C>
>>>

-Chris






More information about the Python-list mailing list