【问题标题】:Returning multiple objects and using them as arguments返回多个对象并将它们用作参数
【发布时间】:2017-02-15 05:38:39
【问题描述】:

我有一个类似这样的函数:

def do_something(lis):
    do something
    return lis[0], lis[1]

以及另一个需要将这两个返回对象作为参数的函数:

def other_function(arg1, arg2):
    pass

我试过了:

other_function(do_something(lis))

但是发生了这个错误:

TypeError: other_function() 缺少 1 个必需的位置参数:'arg2'

【问题讨论】:

  • 显示other_function函数声明

标签: python function functional-programming return arguments


【解决方案1】:

调用other_function 时需要解压缩这些参数。

other_function(*do_something(lis))

根据错误消息,您的其他函数似乎已定义(并且应该定义为)

def other_function(arg1, arg2):
    pass

所以,当您从do_something 返回时,实际上是在返回一个包含(lis[0], lis[1]) 的元组。因此,当您最初调用 other_function 时,您传递了一个元组,而您的 other_function 仍然期待第二个参数。

如果您进一步分解它,您可以看到这一点。以下是在不同处理时返回的外观细分、错误重现和解决方案演示:

返回单个变量将返回结果的元组:

>>> def foo():
...     lis = range(10)
...     return lis[1], lis[2]
...
>>> result = foo()
>>> result
(1, 2)

返回两个变量,解压到每个变量中:

>>> res1, res2 = foo()
>>> res1
1
>>> res2
2

尝试使用 result 调用 other_function,它现在只包含结果的元组:

>>> def other_function(arg1, arg2):
...     print(arg1, arg2)
...
>>> other_function(result)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: other_function() missing 1 required positional argument: 'arg2'

使用 res1res2 调用 other_function 来保存从 foo 返回的每个值:

>>> other_function(res1, res2)
1 2

使用result(您的元组结果)并在对other_function的函数调用中解包:

>>> other_function(*result)
1 2

【讨论】:

    【解决方案2】:

    你可以这样做:

    other_function(*do_something(list))
    

    * 字符将扩展由do_something 返回的tuple

    您的do_something 函数实际上返回了一个tuple,其中包含多个值,但本身只有一个值。

    更多详情请见the doc

    【讨论】:

      猜你喜欢
      • 2011-11-18
      • 2021-06-04
      • 2022-10-12
      • 2023-03-17
      • 2012-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-22
      相关资源
      最近更新 更多