Python class instantiation using name

Inyeol Lee inyeol.lee at siimage.com
Tue Dec 17 17:46:42 EST 2002


On Tue, Dec 17, 2002 at 01:38:06PM -0800, Amol P Dharmadhikari wrote:
>
> 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()
> 

If the class is in module 'foo':

import foo
inst = getattr(foo, "classname")()

If it is in current module:

inst = globals()["classname"]()

Inyeol Lee...




More information about the Python-list mailing list