pra*_*shu 16 python string function
假设我bar在一个名为的模块中有一个函数foo.py.在foo.py中的某个地方,我希望能够从字符串"bar"调用bar().我怎么做?
# filename: foo.py
import sys
def bar():
print 'Hello, called bar()!'
if __name__ == '__main__':
funcname = 'bar'
# Here I should be able to call bar() from funcname
Run Code Online (Sandbox Code Playgroud)
我知道python中存在一些名为'getattr'的内置函数.但是,它需要'模块对象'作为第一个参数.如何获取当前模块的"模块对象"?
mgi*_*son 28
globals可能更容易理解.它返回当前模块__dict__,因此你可以这样做:
func_I_want = globals()['bar'] #Get the function
func_I_want() #call it
Run Code Online (Sandbox Code Playgroud)
如果你真的想要模块对象,你可以从中得到它sys.modules(但你通常不需要它):
import sys.modules
this_mod = sys.modules[__name__]
func = getattr(this_mod,'bar')
func()
Run Code Online (Sandbox Code Playgroud)
请注意,一般情况下,您应该问自己为什么要这样做.这将允许通过字符串调用任何函数 - 这可能是用户输入...如果您不小心让用户访问了错误的函数,这可能会产生潜在的不良副作用.
Ash*_*ary 14
使用保持要调用的函数映射的字典:
if __name__ == '__main__':
funcnames = {'bar': bar}
funcnames['bar']()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
10479 次 |
| 最近记录: |