python - 使用返回函数中的变量作为另一个函数的参数

标签 python function return

我有一个函数,它有 4 个参数定义为:

call(a,b,c,d):

我有另一个函数叫做

return_args() #that returns 4 variables. 

当我执行以下操作时:

call(return_args()) #it errors out saying, that's 1 arguments, not 4 arguments 

我知道我可以将 4 个变量存储在 call() 之前的另一行中,但可以在 call() 行中返回所有变量。

最佳答案

你可以使用*参数解包

call(*return_args())

这是以下内容的简写形式:

a, b, c, d = return_args()
call(a, b, c, d)

甚至

tup = return_args()
call(*tup)

以这种方式使用的 Python 的 * 运算符本质上是说“解压这个元组并将解压后的值作为参数传递给这个函数”。

相关运算符 ** 对关键字参数做了类似的技巧:

def call(arg1=None, arg2=None, **kwargs):
    pass

kwargs = {'arg1': 'test', 'arg3': 'whatever'}
call(**kwargs)

*** 可以一起使用:

def call(*args, **kwargs):
    pass
call(*return_args(), **kwargs)

关于python - 使用返回函数中的变量作为另一个函数的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22380517/

相关文章:

c++ - 返回一个节点类

python - 按索引和列名数组对 Pandas 数据框进行切片

python - 如果键作为值出现在其他地方,则从嵌套字典中删除它们

arrays - linux(树莓派)上使用 spidev 的 SPI

python - "Python closure"适用于函数对象吗?

Flutter删除For循环中的多个列表项(For循环中的多个返回)

python - 使用类对象替换 sys.modules 中的当前模块时,导入的模块变为 None

python - Elasticsearch-IndicesClient.put_settings无法正常工作

bash - shell脚本: Indirect recursion doesn't work as expected (too many repetitions)

exception - 返回什么?错误字符串、带有错误字符串输出的 Bool 或带有异常的 Void