Python class instantiation using name
David Eppstein
eppstein at ics.uci.edu
Tue Dec 17 18:42:54 EST 2002
In article <mailman.1040166033.32587.python-list at python.org>,
Chad Netzer <cnetzer at mail.arc.nasa.gov> wrote:
> On Tuesday 17 December 2002 14:16, holger krekel wrote:
> > Amol P Dharmadhikari wrote:
> > 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 )
Why do you need to concatenate the () within the string and evaluate it,
when it's easier just to do it outside?
newInstance = eval(classname)()
newInstance = eval(classname, othermodule.__dict__)()
--
David Eppstein UC Irvine Dept. of Information & Computer Science
eppstein at ics.uci.edu http://www.ics.uci.edu/~eppstein/
More information about the Python-list
mailing list