Python class instantiation using name
Bengt Richter
bokr at oz.net
Tue Dec 17 19:41:49 EST 2002
On Tue, 17 Dec 2002 13:38:06 -0800, Amol P Dharmadhikari <ad at cs.usfca.edu> wrote:
>Hi All,
>
>I have a question about python, which I did not find answered in
>the FAQs and tutorials.
>
>Is it possible to create an instance of a class using its name?
>If so how?
>
>So in general, if I have a string which contains the name of a class,
>how do I create an instance of that class?
>
>i.e. something similar to what the below java code snippet can do
>Object o = java.lang.Class.forName(className).newInstance()
>
>Please cc me in the reply as I am not subscribed to the list.
Ok, just this once, but in future you can see the latest of this newgroup via google:
http://groups.google.com/groups?hl=en&group=comp.lang.python
with not much delay from posting time. Maybe faster than some long
paths of news forwarding.
>
The following is not tested any more than you see here ;-)
>>> def classForName(name, *args, **kw):
... ns = kw.get('namespace',globals())
... return ns[name](*args)
...
>>> classForName('B')
<__main__.B instance at 0x007E1590>
>>>
>>> class A: pass
...
>>> class B:
... def __init__(self, *args):
... print 'B init got',args
... self.args = args
...
>>> classForName('A')
<__main__.A instance at 0x007E1530>
>>> binst = classForName('B', 123, 'args to B', 456)
B init got (123, 'args to B', 456)
>>> binst.args
(123, 'args to B', 456)
>>> import types
>>> classForName('IntType', 123, namespace=types.__dict__)
123
>>> classForName('FloatType', 123, namespace=types.__dict__)
123.0
Regards,
Bengt Richter
More information about the Python-list
mailing list