gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:10:17 26 4
gpt4 key购买 nike

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

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.

关于python - 如果存在具有相同名称的位置参数,为什么 kwargs 中的键被删除?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23770682/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com