Given a string - execute a function by the same name
Max M
maxm at mxm.dk
Mon Apr 28 18:12:58 EDT 2008
python at bdurham.com skrev:
> I'm parsing a simple file and given a line's keyword, would like to call
> the equivalently named function.
>
> There are 3 ways I can think to do this (other than a long if/elif
> construct):
>
> 1. eval()
>
> 2. Convert my functions to methods and use getattr( myClass, "method" )
>
> 3. Place all my functions in dictionary and lookup the function to be
> called
>
> Any suggestions on the "best" way to do this?
No reason to use eval.
use either getattr(obj, "method")() or functions['method']
They are basically the same thing.
The dict of functions is a bit safer. You don't risk calling a built in
method on your object . Which you risk doing with something like:
getattr(obj, 'join')
--
hilsen/regards Max M, Denmark
http://www.mxm.dk/
IT's Mad Science
More information about the Python-list
mailing list