【问题标题】:pass a parameter which the function will ignore传递函数将忽略的参数
【发布时间】:2020-03-15 20:56:22
【问题描述】:

假设我们有一个带有签名的简单 python 函数:

def foo(first, second, third=50)

当我从main 调用它时,我总是有第一个和第二个参数,但我并不总是有第三个。

当我尝试从我使用的字典中获取第三个时:third = dict['value'] if 'value' in dict.keys() else None

问题是,当我传递这个None 时,我希望函数使用其默认的第三个参数并且为50,但它只使用None。我也试过[]

有没有更优雅的方法,除了调用函数两次,取决于third是否存在,一次有,一次没有,如下?

third = dict['value'] if 'value' in dict.keys() else None
if third:
    foo(first, second, third)
else:
    foo(first, second)

【问题讨论】:

  • 第一个和第二个参数也是这个dict 的元素吗?在这种情况下,请不要隐藏内置名称 - dict。使用描述性变量名称。

标签: python dictionary default-value


【解决方案1】:

试试:

if dict.get('value'):
    def foo(first, second, third)
else:
    def foo(first, second)

【讨论】:

    【解决方案2】:

    像这样重新定义你的函数怎么样:

    def foo(first, second, third):
        if third == None:
            third = 50
        """ Your code here """
    

    third = dict['value'] if 'value' in dict.keys() else 50

    【讨论】:

    • 在您添加第二个选项之前我几乎赞成,该选项将默认参数值从函数的定义中取出。这毁了你本来很好的答案。如果从 100 个不同的地方调用该函数并且您需要将默认值从 50 更改为 40...
    【解决方案3】:

    你可以这样做:

    kwargs = {'third': dict['value']} if 'value' in dict else {}
    foo(first, second, **kwargs)
    

    第一行创建一个kwargs 字典,如果dict 中有value,则它只包含一个键third,否则它是空的。在调用函数时,您可以传播 kwargs 字典。

    【讨论】:

      【解决方案4】:

      Python 中的函数对象有一个特殊的属性__defaults__。这是一个具有默认参数值的元组。因此,您可以轻松地从那里获取 third 的默认值:

      def foo(first, second, third=50):
          return third
      
      dict = {}
      print(foo(10, 20, dict.get('value', foo.__defaults__[0])))  # prints 50
      
      dict = {"value": 100}
      print(foo(10, 20, dict.get('value', foo.__defaults__[0])))  # prints 100
      

      【讨论】:

        【解决方案5】:

        您可以使用列表理解对参数进行分组:

        def foo(first,second,third=50): 
            print(first,second,third) 
        
        args=[ a for a in [10,20,d.get("third",None)] if a!=None ]
        
        foo(*args)                                                                                                           
        10 20 50
        

        【讨论】:

          【解决方案6】:

          我今天遇到了类似的问题。调用您的函数时,请执行以下操作:

          foo(first, second, third=50)
          

          这样传递时,第三个应该取值。

          您可以检查第三次传递的内容

          if None in third:
              # do this
          else:
              # do something else
          

          【讨论】:

            猜你喜欢
            • 2015-06-01
            • 2021-01-20
            • 2019-02-01
            • 2013-09-25
            • 2018-07-30
            • 1970-01-01
            • 2014-12-18
            • 1970-01-01
            • 2013-09-11
            相关资源
            最近更新 更多