gpt4 book ai didi

python - 如何在 Python 中选择性地传递具有非默认值的参数?

转载 作者:行者123 更新时间:2023-11-28 21:45:06 27 4
gpt4 key购买 nike

我有以下方法:

def a(b='default_b', c='default_c', d='default_d'):
# …
pass

我有一些命令行界面,允许提供变量 user_buser_cuser_d 或将它们设置为 - 即简单的 Python argparse 模块。

我想调用这样的电话:

a(b=user_b if user_b is not None,
c=user_c if user_c is not None,
d=user_d if user_d is not None)

如果变量是None,我想使用方法参数的默认值。

我找到的唯一方法是检查用户变量的所有组合:

if not user_b and not user_c and not user_d:
a()
elif not user_b and not user_c and user_d:
a(d)

elif user_b and user_c and user_d:
a(b, c, d)

什么是更有效、更奇特和 Pythonic 的方法来解决我的问题?

最佳答案

arg_dict = {}
if user_b is not None:
arg_dict["b"] = user_b
if user_c is not None:
arg_dict["c"] = user_c
if user_d is not None:
arg_dict["d"] = user_d

a(**arg_dict)

虽然不是很漂亮。

更好的方法是重写函数 a 以接受 None 作为默认答案,然后检查它。 (即 if b is None: b = "default_b")

关于python - 如何在 Python 中选择性地传递具有非默认值的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39877826/

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