Python class instantiation using name
Chad Netzer
cnetzer at mail.arc.nasa.gov
Tue Dec 17 17:58:25 EST 2002
On Tuesday 17 December 2002 14:16, holger krekel wrote:
> Amol P Dharmadhikari wrote:
> > So in general, if I have a string which contains the name of a
> > class, how do I create an instance of that class?
>
> cls = eval(classname)
>
> if the class is defined in the current module. or
>
> cls = eval(classname, othermodule.__dict__)
>
> if the class lives in another module.
That code will bind to the class objects, but won't create
instances of the classes.
I would amend the above code to be:
instance = eval( classname + "()" )
or if it is in a module called "othermodule":
instance = eval( "othermodule." + classname + "()" )
You could also use string substitution:
instance = eval( "othermodule.%s()" % classname )
--
Bay Area Python Interest Group - http://www.baypiggies.net/
Chad Netzer
cnetzer at mail.arc.nasa.gov
More information about the Python-list
mailing list