为什么使用Python的可变长度参数而不是传入列表/字典?

时间:2014-10-28 16:04:58

标签: python coding-style variadic-functions

Python允许您声明类似

的函数
def print_all(*arguments):
    for a in arguments:
        print(a)
print_all(1,2,3)

允许传递可变数量的数据。对于我而言,这似乎比构建列表或字典更具可读性,并将其作为参数传递给我。

def print_all2(things_to_print):
    for thing in things_to_print:
        print(thing)
things_to_print = [1,2,3]
print_all2(things_to_print)

第二个选项允许您为参数指定正确的名称。什么时候最好使用* arguments技术?是否有时候使用*参数更多Pythonic?

2 个答案:

答案 0 :(得分:8)

  

有没有时候使用*参数更像Pythonic?

不仅"更多pythonic",但它通常必要

当您不知道函数将收到多少个参数时, 需要<{1}}。

例如,想想装饰者:

*args

答案 1 :(得分:7)

非常基于意见,但有时你想使用一个提供内联参数的函数。它看起来更清晰:

function("please", 0, "work this time", 2.3)

比:

function(["please", 0, "work this time", 2.3])

事实上,有一个很好的例子,你甚至在你的问题中提到:print!想象一下,每次打印时都需要创建一个列表:

print(["please print my variable", x, " and another:", y])
print([x])

乏味。