python中函数的用途-Python中函数调用时*和**的作用?

If the form “*identifier” is present, it is initialized to a tuple receiving any excess positional parameters, defaulting to the empty tuple. If the form “**identifier” is present, it is initialized to a new ordered mapping receiving any excess keyword arguments, defaulting to a new empty mapping of the same type. Parameters after “*” or “*identifier” are keyword-only parameters and may only be passed used keyword arguments.

若存在“*identifier”形式,则它被初始化成一个收取任何多出的位置形参的元组,默认是空元组。若存在“**identifier”形式,则它被初始化成一个收取任何多出的关键词实参的新映射,默认是同类型的新空映射。“*”或“*identifier”后的形参是仅限关键词的形参,而且只能用关键词实参传递。

If the syntax *expression appears in the function call, expression must evaluate to an iterable. Elements from these iterables are treated as if they were additional positional arguments. For the call f(x1, x2, *y, x3, x4), if y evaluates to a sequence y1, ..., yM, this is equivalent to a call with M+4 positional arguments x1, x2, y1, ..., yM, x3

若语法 *expression 出现于函数调用中,则 expression 必须求值为可迭代(类型)。来自这些可迭代(类型)的元素被处理成如同它们是附加的位置实参。对于调用 f(x1, x2, *y, x3, x4) ,若 y 求值为序列 y1, ..., yM ,则这等价于有 M+4 个位置实参 x1, x2, y1, ..., yM, x3 的调用。

If the syntax **expression appears in the function call, expression must evaluate to a mapping, the contents of which are treated as additional keyword arguments. If a keyword is already present (as an explicit keyword argument, or from another unpacking), a TypeError exception is raised.

若语法 **expression 出现于函数调用中,则表达式必须求值为映射,其内容被当做附加的关键词实参。若以存在关键词(如显式关键词实参,或来自另一解包),则引发 TypeError 异常。

还有很多细节先不引用了……

简言之,函数头里的 * 和 ** 是把有对应参数以外的实参打包成一个形参。类似一个类型修饰符。

而函数调用表达式里的 * 和 ** 则是把恰当类型的表达式解包成多个实参。类似一个运算符。

然后!

(iterable , * [ , default=obj , key=func ] )

你引用的这东西根本就不是调用函数时的形式,它是函数调用方式的一个说明。

(我百度一下后发现这段是写在注释里的……)

实际调用时 default 和 key 不用方括号括着,也没有额外的逗号。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值