gpt4 book ai didi

python - 将函数列表(带参数)作为 python 中的输入

转载 作者:行者123 更新时间:2023-12-01 05:12:53 24 4
gpt4 key购买 nike

我的意图是这样做:

config = {"methods": ["function1(params1)", "function2(params2)"] }

这是我从 json 文件中读取的。因此,要使用它,我需要将其传递给另一个函数,如下所示:

for method in config[methods]:
foo(global()[method])

我知道这不起作用,因为全局变量仅将函数名称从字符串转换为函数,但我也需要它也适用于带参数的函数。

我也想到了这一点:

config = {"methods": [("function1", params1) , ("function2", params2)] }
for method in config[methods]:
foo(global()[method[0]](method[1]))

这可以工作,但我可能有一些不需要参数的函数。我不想对元组中的第二个条目是否存在进行条件检查。

还有其他办法解决这个问题吗?我愿意改变整个方法,包括输入格式。请大家提出建议。

最佳答案

这是一个适用于任意数量参数的简化示例:

from re import findall

def a(*args):
for i in args:
print i

config = {"methods": ["a('hello')", "a('hello','bye')", "a()"]}

for i in config['methods']:
x,y = findall(r'(.*?)\((.*?)\)', i)[0]
y = [i.strip() for i in y.split(',')]
globals()[x](*y)


[OUTPUT]
'hello'
'hello'
'bye'

DEMO

关于python - 将函数列表(带参数)作为 python 中的输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23800053/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com