【问题标题】:Set default parameter value in function to value of another parameter [duplicate]将函数中的默认参数值设置为另一个参数的值[重复]
【发布时间】:2023-03-11 05:35:01
【问题描述】:

有没有办法将函数中的默认参数值设置为另一个参数?

def (input1, input2 = input1)

我想我可以做如下所示的事情,但想知道是否有更好的方法

def (input1, input2 = 'blank')
      If input2 == 'blank':
           input2 = input1

【问题讨论】:

  • 不,你不能,因为在input2=input1 的声明中,input1 需要已经定义
  • @bdbd 不正确。去测试一下。
  • @PeterJones 测试def test(x, y=x):。它说NameError: name 'x' is not defined,所以你不能

标签: python default-arguments


【解决方案1】:

你可以试试这个。也许再澄清一点可以帮助我们为您提供更多帮助。

def do_stuff(input1, input2 = None):
    if input2 is None:
       input2 = input1

你已经很接近了。

【讨论】:

    【解决方案2】:

    您不能将局部变量分配给参数,因为在函数定义期间尚未定义该变量。

    我们通常使用None 来捕捉缺失值:

    def add2(i1, i2=None):
        if i2 is None:
            i2 = i1
        return i1 + i2
    

    在此函数中,i1 是必填项。如果未提供,i2 将设置为与 i1 相同的值。

    add2(10, 2)
    # > 12
    add2(9)
    # > 18
    

    【讨论】:

      【解决方案3】:

      我更喜欢使用创建类作为参数

      class helper:
          input 2 = 'blank'
          input 3 = 1
      def xx(input1, helper):
          if input1 == helper.input2:
              input1 == helper.input3
      

      这是一个例子,你可以使用一个类来帮助你。

      【讨论】:

        猜你喜欢
        • 2015-11-05
        • 2017-02-03
        • 2018-01-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-03
        • 2010-10-28
        相关资源
        最近更新 更多