您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在条件条件下传递关键字参数的Python方法

在条件条件下传递关键字参数的Python方法

connect_kwargs = dict(username="foo")

if authenticate: connect_kwargs[‘password’] = “bar” connect_kwargs[‘otherarg’] = “zed” connect(**connect_kwargs)

当您可以将一组复杂的选项传递给函数时,这有时会很有帮助。在这种简单的情况下,我认为您有更好的选择,但是可以将其视为 更pythonic, 因为它不会username="foo"像OP那样重复两次。

password = "bar" if authenticate else None

otherarg = “zed” if authenticate else None connect(username=”foo”, password=password, otherarg=otherarg)

python 2022/1/1 18:28:16 有431人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶