作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有以下方法:
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)
什么是更有效、更奇特和 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/
我是一名优秀的程序员,十分优秀!