4.8.4.Python任意参数列表

【原文】

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参数之后的任何形参都是仅限关键字参数,这意味着它们只能用作关键字参数而不是位置参数。

【拓展】
实例1:调用函数时,传递任意数量的参数。

实例2,在*arg之前,定义0个或多个普通参数。这些普通参数在*args之前被处理,而*args则会收集所有剩余的参数。这种灵活性可应用在编写通用函数或处理用户输入时。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值