我有一个自定义的dict类(collections.MutablMapping
),实际的对象有点复杂,但我的问题很简单,如何将自定义参数传递到__init__
方法之外转到*args
**kwargs
dict()
class TestDict(collections.MutableMapping):
def __init__(self, *args, **kwargs):
self.store = dict()
self.update(dict(*args, **kwargs))
self.custom_name = None #how to pass custom name outside of the dict args?
def __getitem__(self, key):
return self.store[key]
def __setitem__(self, key, value):
self.store[key] = value
def __delitem__(self, key):
del self.store[key]
def __len__(self):
return len(self.store)
def __iter__(self):
return iter(self.store)
def __repr__(self):
return str(self.store)
编辑:(我的评论的代码,再次不确定这是否是正确的方法,特别是如果有多个keyname参数放入self而不是dict()):
def __init__(self, *args, **kwargs):
try: custom_name = kwargs.pop('custom_name')
except: custom_name = None
self.store = dict()
self.update(dict(*args, **kwargs))
self.custom_name = custom_name
答案 0 :(得分:3)
在Python 3中,您可以:
def __init__(self, *args, custom_name=None, **kwargs):
self.custom_name = custom_name
# do your stuff...
在Python 2中,您可以:
def __init__(self, *args, **kwargs):
try:
self.custom_name = kwargs["custom_name"]
del kwargs["custom_name"]
except:
self.custom_name = None
# do your stuff...
任何一个版本都会像这样实例化:
d = TestDict({"spam": "egg"}, custom_name="my_custom_dict")