Can string be callable as a method ?

Steven D'Aprano steve at REMOVE.THIS.cybersource.com.au
Mon May 28 10:46:06 EDT 2007


On Mon, 28 May 2007 06:45:47 -0700, Jia Lu wrote:

> Hi all
>  I tried to scan a directory and __import__ all modules ,
> <log>
> imported module: help
> imported module: __init__
> imported module: hi
> imported module: thanks
> 
> and I scaned all methods in them, and put them to a list like:
> 
> [['f_chelp', 'f_help'], [], ['f_exclaim', 'f_hi', 'random'],
> ['f_thanks', 'random']]
> 
> But how can I call them from that list??


>>> import math
>>> dir(math)
['__doc__', '__file__', '__name__', 'acos', 'asin', ... ]
>>> 
>>> math.__dict__['acos'](0)
1.5707963267948966
>>> getattr(math, 'asin')(0)
0.0

Instead of storing the names of the functions, better to store the
functions themselves:

>>> my_list = [math.acos, math.asin]
>>> my_list[0](1)
0.0


Hope this helps,


-- 
Steven.




More information about the Python-list mailing list