Skip to main content
 首页 » 编程设计

python之如果存在具有相同名称的位置参数,为什么 kwargs 中的键被删除

2025年05月04日20mq0036

我刚遇到这种让我感到惊讶的行为:

def my_func(a=4, **kwargs): 
    print kwargs 

演示:

>>> my_func(a=5, b=6) 
{'b': 6}  # I was expecting {'a' : 4, 'b' : 6} 
          # Maybe {'a' : 5, 'b' : 6} 

此外,如果我得到:

语法错误:关键字参数重复

如在

>>> my_func(a=4, a=5) 
  File "<stdin>", line 1 
SyntaxError: keyword argument repeated 

或TypeError: my_func() got multiple values for keyword argument 'a'

如在

>>> my_func(a=4, **{'a' : 5, 'b' : 6}) 
Traceback (most recent call last): 
  File "<stdin>", line 1, in <module> 
TypeError: my_func() got multiple values for keyword argument 'a' 

python 删除关键字'a'遵循什么规则?

也许我遗漏了一些明显的东西,或者一个关键的术语,但我无法通过搜索找到解决方案。

请您参考如下方法:

a 没有被删除,它只是没有被包含在 **kwargs 中,因为您在函数定义中明确定义了它。因此,如果我编辑您的原始示例:

def my_func(a=4, **kwargs): 
    print kwargs 
    print a 

然后测试一下:

>>> my_func(a=5, b=7) 
{'b': 7} 
5 

**kwargs 参数用于收集函数调用中给出的可选关键字参数,这些参数未明确包含在函数定义中。由于您在 my_func 的定义中包含了 a=4,因此它不会包含在 **kwargs 中。

Python documentation 中提到了这一点(强调我的):

When a final formal parameter of the form **name is present, it receives a dictionary (see Mapping Types — dict) containing all keyword arguments except for those corresponding to a formal parameter.