[英]How can I configure exuberant-ctags to ignore python keyword arguments?
[英]How to ignore extra keyword arguments in 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的参数变化?
你可以让Test.__init__
接受额外的**kwargs
class Test(object):
def __init__(self, id, name, **kwargs):
self.id = id
self.name = name
这样就可以了,只需更新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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.