位置参数 python 速成课程?

问题描述 投票:0回答:1
def build_profile(first, last, **user_info):
"""Build a dictionary containing everything we know about a user."""
user_info['first_name'] = first
user_info['last_name'] = last
return user_info


user_profile = build_profile('albert', 'einstein',
                        location='princeton',
                        field='physics')
print(user_profile)

输出:

{'location': 'princeton', 'field': 'physics', 'first_name': 'albert', 'last_name': 'einstein'}

我不明白为什么键值first_name和last_name放在最后?它们不是应该放在位置和字段之前吗?因为位置参数??

请帮忙。

python arguments keyword-argument arbitrary-values positional-argument
1个回答
1
投票

如果您希望传入函数的位置参数出现在传入的

**kwargs
之前,您可以使用
dict(..., **kwargs)
方法来构建新的
dict
对象:

def build_profile(first, last, **addl_info):
    """Build a dictionary containing everything we know about a user."""
    user_info = {'first_name': first, 'last_name': last, **addl_info}
    return user_info


user_profile = build_profile('albert', 'einstein',
                             location='princeton',
                             field='physics')
print(user_profile)

出:

{'first_name': 'albert', 'last_name': 'einstein', 'location': 'princeton', 'field': 'physics'}
© www.soinside.com 2019 - 2024. All rights reserved.