Python中如何使用任意数量的关键字实参(**kwargs)?
###代码###
def build_profile(first,last,**user_info):
profile = {}
profile[‘first_name’] = first
profile[‘last_name’] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile(‘albert’,‘einstein’,location=‘princeton’, field=‘physics’)
print(user_profile)
已上讲道理应该打印:{‘first_name’: ‘albert’, ‘last_name’: ‘einstein’, ‘location’: ‘princeton’,‘field’:‘physics’}
但是实际只有:{‘first_name’: ‘albert’, ‘last_name’: ‘einstein’, ‘location’: ‘princeton’},没任何报错。Python 版本:3.6.5
Python中如何使用任意数量的关键字实参(**kwargs)?
https://paste.ubuntu.com/p/NkrJcBw92m/ 这个代码试了一下没问题……
在Python里,用 **kwargs 就能搞定任意数量的关键字参数。它会把所有传入的关键字参数打包成一个字典,你在函数内部直接操作这个字典就行。
看这个例子,一个记录用户信息的函数:
def build_profile(**kwargs):
"""收集任意数量的关键字参数,返回一个字典"""
profile = {}
for key, value in kwargs.items():
profile[key] = value
return profile
# 使用方式
user_profile = build_profile(name='Alice', age=30, city='New York', job='Engineer')
print(user_profile)
# 输出:{'name': 'Alice', 'age': 30, 'city': 'New York', 'job': 'Engineer'}
关键点:
**kwargs必须放在所有参数的最后。- 参数名
kwargs是约定俗成的,但你可以用别的名字,比如**info,前面的双星号**才是关键。 - 它经常和
*args(接收任意数量的位置参数)一起用,顺序必须是*args在前,**kwargs在后。
再给个更实用的例子,结合固定参数和 **kwargs 来配置一个设置项:
def configure_settings(base_url, timeout=10, **extra_settings):
"""基础配置加上额外的任意设置"""
config = {
'base_url': base_url,
'timeout': timeout,
}
config.update(extra_settings) # 把额外的设置更新进去
return config
# 调用
app_config = configure_settings('https://api.example.com', timeout=30, retries=3, cache=True)
print(app_config)
# 输出:{'base_url': 'https://api.example.com', 'timeout': 30, 'retries': 3, 'cache': True}
简单说,用 ** 接住所有关键字参数,在函数里当字典处理就行。
谢谢,不知道为啥,我这边打印出来就是少了以后一对键值。
django 里的? django 里的 field 可能是保留字段。
试下把 field 删掉呢? location 还会有吗?
不是 django
跟这个没关系吧。**user_info 是可以传入多个实参的。
代码没问题的,我猜你的 return 写错了位置
楼上猜的很可能是真相。
def build_profile(first,last,**user_info):
profile = {}
profile[‘first_name’] = first
profile[‘last_name’] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile(‘albert’,‘einstein’, location=‘princeton’, field=‘physics’)
print(user_profile)
{‘first_name’: ‘albert’, ‘last_name’: ‘einstein’, ‘location’: ‘princeton’, ‘field’: ‘physics’}
def build_profile(first,last,**user_info):
profile = {}
profile[‘first_name’] = first
profile[‘last_name’] = last
for key,value in user_info.items():
profile[key] = value
return profile
user_profile = build_profile(‘albert’,‘einstein’, location=‘princeton’, field=‘physics’)
print(user_profile)
{‘first_name’: ‘albert’, ‘last_name’: ‘einstein’, ‘location’: ‘princeton’}
这个错误明显很不正常,那你显然要多试试各种可能性,通过错误的表现来排查问题
如果你觉得一切正常,那怎么排查的出问题呢?多打点 print,多用几组数据测一下,而不是上来论坛提问。
这种问题十有八九是你犯了一个非常愚蠢的错误,但是没有注意到。与其让我们来猜,还不如你多去自己调试下。
我也不想多说了,你自己体会下吧
受教了
大神猜对了,犯了低级错误。
上面缩进不了,
检查是不是把 return 写进 for 里面了。
另外假如只是把参数又传出来,直接这样写就好:
profile.update(**user_info)
已解决,谢谢答复。

