这是我的问题我定义了许多函数,我想循环遍历这些函数的列表,并以正确的顺序一次运行一个.
def one():
print "One "
def two():
print "Two "
def three(): "Three "
print "Three "
arr = ('one','two','three')
for fnc in arr:
<some how run the function name in the variable fnc>
Run Code Online (Sandbox Code Playgroud)
感谢任何帮助,因为我是python和django的初学者.
Python函数是一阶对象; 把它们按顺序排列:
arr = (one, two, three)
for fnc in arr:
fnc()
Run Code Online (Sandbox Code Playgroud)
您也可以存储字符串,但是您需要先将它们转换回函数对象.那只是你不需要做的额外繁忙工作.
您仍然可以将字符串转换为对象; 该globals()
函数为您提供当前全局命名空间作为字典,因此globals()['one']
为您提供名称引用的对象one
,但这也可以让您访问模块中的每个全局; 如果你犯了一个错误,它可能导致很难跟踪错误甚至安全漏洞(因为最终用户可能会滥用你不打算调用的函数).
如果你真的需要将名称映射到函数,因为,比如说,你需要从只产生字符串的其他东西中获取输入,请使用预定义的字典:
functions = {
'one': one,
'two': two,
'three': three,
}
Run Code Online (Sandbox Code Playgroud)
并将您的字符串映射到该函数:
function_to_call = 'one'
functions[function_to_call]()
Run Code Online (Sandbox Code Playgroud)
您的函数名称不需要与此处的字符串值匹配.通过使用专用字典,您可以限制可以调用的内容.
归档时间: |
|
查看次数: |
1397 次 |
最近记录: |