python-3.x - 使用字符串列表执行带参数的函数
问题描述
我想使用列表对象按名称调用函数,将参数传递给每个函数,而列表用于循环。这些函数必须作为字符串引用,因为在实际脚本中这些函数是通过命令行输入获取的。
功能
我有以下功能:
def sum_a(x):
x + 1000
def sum_b(x):
x + 100
def sum_c(x):
x + 1
打电话
我想执行函数sum_a
和sum_c
for 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'
解决方案
您可以通过名称来引用函数。它们的行为就像变量一样。
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)
推荐阅读
- javascript - 打开多个不同的 iframe
- reporting-services - 在 SSRS 的圆环图中添加文本
- rabbitmq - RabbitMQ - 发布到队列或交换
- azure - 使用一个 Deploy 管理多个 Pod
- jquery - 在 jquery-mobile 中使用 ajax 数据填充页面并不总是有效
- java - Android OkHttp3 java.io.IOException: stream closed
- php - 引导联系表不发送电子邮件(FormTools 也没有)
- arrays - Powershell -notin 数组不会触发 if 语句
- amazon-redshift - Amazon Redshift 中的分号和单引号
- ios - How to record an audio stream for save it in file / swift 4.2