[问题记录]关键字参数异常(TypeError: __init__() got multiple values for keyword argument 'name')

异常

TypeError: init() got multiple values for keyword argument 'name'

例子

d = {'id':'1','sex':1,'org_id':'2','name':'hh','test':'ttt'}

class Person():
   def __init__(self, id, name, **kw):
       self.id = id
       self.name = name
       print kw

p = Person(d['id'], d['name'], **d)

======Output======
Traceback (most recent call last):
 File "xxxxxx", line 26, in 
   p = Person(d['id'], d['name'], **d)
TypeError: __init__() got multiple values for keyword argument 'id'

原因

字典d里面还存在关键字'id‘,python解释器报错

解决方案:

有两种

#删除字典d中'id','name'这两个关键字
d = {'id':'1','sex':1,'org_id':'2','name':'hh','test':'ttt'}
id = d['id']
name = d['name']
del d['id']
del d['name']

class Person():
    def __init__(self, id, name, **kw):
        self.id = id
        self.name = name
        print kw

p = Person(id, name, **d)

======Output=====
{'test': 'ttt', 'org_id': '2', 'sex': 1}

或者

d = {'id':'1','sex':1,'org_id':'2','name':'hh','test':'ttt'}
id = d['id']
name = d['name']

class Person():
    def __init__(self, id, name, **kw):
        self.id = id
        self.name = name
        print kw

p = Person(**d)

====Output=====
{'test': 'ttt', 'org_id': '2', 'sex': 1}

你可能感兴趣的:([问题记录]关键字参数异常(TypeError: __init__() got multiple values for keyword argument 'name'))