【原文】
4.8.4. Arbitrary Argument Lists
Finally, the least frequently used option is to specify that a function can be called with an arbitrary number of arguments. These arguments will be wrapped up in a tuple (see Tuples and Sequences). Before the variable number of arguments, zero or more normal arguments may occur.
def write_multiple_items(file, separator, *args): file.write(separator.join(args))
Normally, these variadic arguments will be last in the list of formal parameters, because they scoop up all remaining input arguments that are passed to the function. Any formal parameters which occur after the *args
parameter are ‘keyword-only’ arguments, meaning that they can only be used as keywords rather than positional arguments.
>>>
>>> def concat(*args, sep="/"): ... return sep.join(args) ... >>> concat("earth", "mars", "venus") 'earth/mars/venus' >>> concat("earth", "mars", "venus", sep=".") 'earth.mars.venus'
【译】
4.8.4.任意参数列表
最后,最不常用的选项是用可以接收任意数量的参数调用函数,这些参数会被包装在一个元组中(参见元组和序列)。在任意数量的参数之前,可能会出现0个或者更多的正常参数。
通常,任意参数在形参列表的最后,因为它们收集了输入给函数的所有剩余参数。出现在所有*args参数之后的任何形参都是仅限关键字参数,这意味着它们只能用作关键字参数而不是位置参数。