我想使用列表对象按名称调用函数,将参数传递给每个函数,而列表则在循环中使用。 必须将这些函数引用为字符串,就像在实际脚本中一样,这些字符串是通过命令行输入获取的。
我具有以下功能:
def sum_a(x):
x + 1000
def sum_b(x):
x + 100
def sum_c(x):
x + 1
我想为sum_a
执行功能sum_c
和x = 9
。
functions_to_call = ['sum_a', 'sum_c']
x = 9
for each_call in functions_to_call:
getattr(globals(), each_call)()
---------------------------------------------------------------------------
AttributeError Traceback (most recent call last)
<ipython-input-14-9f12b9113b60> in <module>()
1 for each_call in functions_to_call:
----> 2 getattr(globals(), each_call)()
3
AttributeError: 'dict' object has no attribute 'sum_a'
答案 0 :(得分:2)
您可以通过函数名称来引用它们。它们的行为就像变量。
functions_to_call = [sum_a, sum_c]
x = 9
for each_call in functions_to_call:
each_call(x)
如果要按名称引用功能:
functions_to_call = ['sum_a', 'sum_c']
x = 9
for each_call in functions_to_call:
globals()[each_call](x)
答案 1 :(得分:1)
最好直接引用这些函数:
functions_to_call = [sum_a, sum_c]
x = 9
for f in functions_to_call:
f(x)
对于您的特定问题,getattr
在字典中搜索那些属性,但是您想要访问字典,为此您可以使用operator.itemgetter
:
>>> from operator import itemgetter
>>> x = 10
>>> itemgetter("x")(globals())
10
最终版本如下:
from operator import itemgetter
functions_to_call = ['sum_a', 'sum_c']
x = 9
for each_call in map(itemgetter, functions_to_call):
each_call(globals())(x)
无论如何,您不应该这样使用globals
,最好使用寻址字典:
funcs = {
"sum_a" : sum_a,
"sum_c" : sum_c
}
functions_to_call = ['sum_a', 'sum_c']
x = 9
for each_call in functions_to_call:
funcs.get(each_call, lambda *_: print("Selected function do not exist"))(x)