我有以下方法:
def a(b='default_b', c='default_c', d='default_d'):
# …
pass
我有一些命令行界面,允许提供变量 user_b
、user_c
、user_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)
什么是更高效、更奇特、更Python式的方法来解决我的问题?
最佳答案
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
作为默认答案,然后检查它。 (即如果 b 为 None:b = "default_b"
)
关于python - 如何在 Python 中选择性地传递带有非默认值的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39877826/