gpt4 book ai didi

python - 按名称动态地将参数传递给函数

转载 作者:行者123 更新时间:2023-12-02 07:02:16 25 4
gpt4 key购买 nike

是否可以动态设置传递给函数的参数名称?

像这样:

def func(one=None, two=None, three=None, four=None):
...

params = ("one","two","three","four",)
for var in params:
tmp = func(var=value)

最佳答案

是的,与 keyword argument unpacking :

def func(one=None, two=None, three=None, four=None):
return (one, two, three, four)

params = ("one", "two", "three", "four")
for var in params:
tmp = func(**{var: "!!"})
print(tmp)

输出:

('!!', None, None, None)
(None, '!!', None, None)
(None, None, '!!', None)
(None, None, None, '!!')

关于python - 按名称动态地将参数传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27541116/

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