You need to enable JavaScript to run this app. 使用**kwargs传递对象出现意外关键字参数报错如何解决
优惠活动
大模型
产品
解决方案
定价
更多

使用**kwargs传递对象出现意外关键字参数报错如何解决

错误原因

  1. 调用message_friends(**user1)时,**运算符会把user1字典拆解为name='Gandalf'、wizard=True两个独立的关键字参数传入函数
  2. 你定义的message_friends(user)仅接受1个名为user的参数,没有声明name、wizard对应的形参,因此抛出参数不匹配的错误
  3. 额外提醒:函数内部的print(user.name)写法也有问题,Python字典不支持.运算符取属性值,后续运行到此处也会报错,需要改为user['name']的取值方式。

修复方案

方案1:调整调用方式(保留原函数定义)

直接把整个user1字典作为参数传入,不需要用**拆解,修改最后一行调用代码即可:

# 把原来的message_friends(**user1)改为
message_friends(user1)

同时修改函数内的print(user.name)为print(user['name'])。

方案2:调整函数定义(保留原**传参方式)

如果需要保留**user1的传参写法,修改函数的形参定义,用**把传入的关键字参数重新打包为字典:

user1 = {
    'name': 'Gandalf',
    'wizard': True
}

def authenticated(func):
    def inner_func(*args, **kwargs):
        print(kwargs)
        if kwargs['wizard']:
            print('(:**********:)')
        return func(*args, **kwargs)    
    return inner_func
    
    
@authenticated
# 此处修改形参为**user,接收所有传入的关键字参数并打包为user字典
def message_friends(**user):
    print(user)
    # 修改字典取值写法
    print(user['name'])
    print('message has been sent')
    print(user.items()) 
     
    for key, value in user.items(): 
        print(key, value)
        print (type((key, value)))
    print('**********')

message_friends(**user1)

内容的提问来源于stack exchange,提问作者Nosail

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 11:24:03