请教: Python 使用任意数量的关键字实参

2018-09-25 13:57:02 +08:00
 krisbai
###代码###
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
1326 次点击
所在节点    Python
14 条回复
ysc3839
2018-09-25 14:02:07 +08:00
https://paste.ubuntu.com/p/NkrJcBw92m/ 这个代码试了一下没问题……
krisbai
2018-09-25 14:07:30 +08:00
@ysc3839 谢谢,不知道为啥,我这边打印出来就是少了以后一对键值。
est
2018-09-25 14:16:45 +08:00
django 里的? django 里的 field 可能是保留字段。
loryyang
2018-09-25 14:18:31 +08:00
试下把 field 删掉呢? location 还会有吗?
krisbai
2018-09-25 14:32:38 +08:00
@est 不是 django
krisbai
2018-09-25 14:33:59 +08:00
@loryyang 跟这个没关系吧。**user_info 是可以传入多个实参的。
Marmot
2018-09-25 14:38:47 +08:00
代码没问题的,我猜你的 return 写错了位置
Sylv
2018-09-25 14:50:37 +08:00
楼上猜的很可能是真相。
freakxx
2018-09-25 15:03:49 +08:00
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'}
loryyang
2018-09-25 15:15:52 +08:00
@krisbai 这个错误明显很不正常,那你显然要多试试各种可能性,通过错误的表现来排查问题
如果你觉得一切正常,那怎么排查的出问题呢?多打点 print,多用几组数据测一下,而不是上来论坛提问。
这种问题十有八九是你犯了一个非常愚蠢的错误,但是没有注意到。与其让我们来猜,还不如你多去自己调试下。
我也不想多说了,你自己体会下吧
krisbai
2018-09-25 15:18:33 +08:00
@loryyang 受教了
krisbai
2018-09-25 15:19:17 +08:00
@Marmot 大神猜对了,犯了低级错误。
freakxx
2018-09-25 15:20:55 +08:00
上面缩进不了,

检查是不是把 return 写进 for 里面了。

另外假如只是把参数又传出来,直接这样写就好:
profile.update(**user_info)
krisbai
2018-09-25 15:21:58 +08:00
@freakxx 已解决,谢谢答复。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/492343

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX