简体   繁体   English

Python函数参数传递顺序

[英]Python function argument passing sequence

Following code is incorrect: 以下代码不正确:

def add(a, b, c):
    return a + b + c
args = (2, 3)

add(a = 1, *args)
TypeError: add() got multiple values for keyword argument 'a'

I've seen some example in python docs , but I still don't know why there's an error, can anybody explain in detail? 我已经在python docs中看到了一些示例,但是我仍然不知道为什么会有错误,有人可以详细解释吗?

When applying the arguments, Python first fills in the positional arguments, then the keyword arguments. 应用自变量时,Python 首先填充位置自变量, 然后填充关键字自变量。

In your specific case, *args is then applied firsts, so the first positional argument is passed 2 , the second is passed 3 . 在您的特定情况下,首先应用*args ,因此第一个位置参数传递2 ,第二个位置参数传递3 The first argument is a here. 第一个参数是a在这里。

Then the a = 1 is applied, and Python finds that you already applied a value to it. 然后应用a = 1 ,Python发现您已经对其应用了一个值。

In other words, Python cannot and will not take positional arguments out of consideration when you use one as a keyword argument. 换句话说,当您将位置参数用作关键字参数时,Python不会也不会考虑位置参数。 Just because you used a as keyword argument does not make it ineligible as a positional argument. 仅仅因为你使用a作为关键字参数并不能使它作为资格位置参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM