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

发布于 2021-01-29 14:58:52

有没有更Python的方式来做到这一点?

if authenticate:
    connect(username="foo")
else:
    connect(username="foo", password="bar", otherarg="zed")
关注者
0
被浏览
73
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。
    1. 您可以将它们添加到类似kwarg的列表中:
      connect_kwargs = dict(username="foo")
      

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


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

    1. 尽管仅当您知道默认参数是什么时,它仍然可以使用这种替代方法。由于if子句重复,我也不会认为它非常“ pythonic” 。
      password = "bar" if authenticate else None
      

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



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看