class Test(object):
def __init__(self, id, name):
self.id = id
self.name = name
def foo(d):
return Test(**d)
# this works well
d = {'id': 'aaa', 'name': 'aaa-name'}
foo(d)
# this would not work well, because of parameter variations, a external para add into dict d.
d = {'id': 'aaa', 'name': 'aaa-name', 'test1': 'test1'}
# traceback
TypeError: __init__() got an unexpected keyword argument 'test1'
是否有任何方法可以忽略dict d的参数变化?
答案 0 :(得分:4)
您可以Test.__init__
接受额外的**kwargs
class Test(object):
def __init__(self, id, name, **kwargs):
self.id = id
self.name = name
答案 1 :(得分:2)
这样就可以了,只需更新self.__dict__
class Test(object):
def __init__(self, id, name, **kwargs):
self.id = id
self.name = name
self.__dict__.update(kwargs)
示例:
In[2]: class Test(object):
def __init__(self, id, name, **kwargs):
self.id = id
self.name = name
self.__dict__.update(kwargs)
In[3]: d = {'id': 'aaa', 'name': 'aaa-name', 'test1': 'test1'}
In[5]: t = Test(**d)
In[6]: t.id
Out[5]: 'aaa'
In[7]: t.name
Out[6]: 'aaa-name'
In[8]: t.test1
Out[7]: 'test1'
修改强>
要忽略附加内容,请不要使用@ wong2中的kwargs:
class Test(object):
def __init__(self, id, name, **kwargs):
self.id = id
self.name = name