首页 > 解决方案 > 使用字符串列表执行带参数的函数

问题描述

我想使用列表对象按名称调用函数,将参数传递给每个函数,而列表用于循环。这些函数必须作为字符串引用,因为在实际脚本中这些函数是通过命令行输入获取的。

功能

我有以下功能:

 def sum_a(x):
     x + 1000


 def sum_b(x):
     x + 100


 def sum_c(x):
     x + 1

打电话

我想执行函数sum_asum_cfor 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'

标签: python-3.xlistfunctionnamespaces

解决方案


您可以通过名称来引用函数。它们的行为就像变量一样。

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)

推荐阅读