如何在Python中忽略额外的关键字参数?

时间:2016-03-08 08:07:28

标签: python

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的参数变化?

2 个答案:

答案 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