这是我的问题我定义了许多函数,我想循环遍历这些函数的列表,并按正确的顺序一次运行一个函数。
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>
感谢任何帮助,因为我是python和django的初学者。
答案 0 :(得分:7)
Python函数是一阶对象;把它们按顺序排列:
arr = (one, two, three)
for fnc in arr:
fnc()
您也可以存储字符串,但是您需要先将它们转换回函数对象。那只是你真正不需要的额外繁忙工作。
您仍然可以将字符串转换为对象; globals()
function为您提供当前全局命名空间作为字典,因此globals()['one']
为您提供了名称one
引用的对象,但这也可以让您访问每个你的模块中的em> global;如果你犯了一个错误,可能会导致很难跟踪错误甚至安全漏洞(因为最终用户可能会滥用你不打算调用的函数)。
如果你真的需要将名字映射到函数,因为你需要从只生成字符串的其他东西中获取输入,请使用预定义的字典:
functions = {
'one': one,
'two': two,
'three': three,
}
并将您的字符串映射到函数:
function_to_call = 'one'
functions[function_to_call]()
您的函数名称不需要与此处的字符串值匹配。通过使用专用字典,您可以限制可以调用的内容。
答案 1 :(得分:1)
这取决于函数的定义位置,但如果它们在当前上下文中,您可以通过从globals
函数中检索它们来获取它们的引用:
def fn():
return ":)"
for f in['fn']:
print globals()[f]()
答案 2 :(得分:0)
似乎工作......
method_name = 'one'
possibles = globals().copy()
possibles.update(locals())
method = possibles.get(method_name)
if not method:
raise Exception("Method %s not implemented" % method_name)
returned_value = method()
答案 3 :(得分:0)
对于您的具体示例,只需使用eval:
arr = ('one','two','three')
for fnc in arr:
eval(fnc + '()')
请注意,某些人使用eval()
为considered bad practice。