2014-10-10 67 views
2

我有一个自定义字典类(collections.MutablMapping),实际的对象是稍微复杂一些,但我的问题很简单,我怎么可以通过自定义参数成的*args**kwargs是去dict()__init__方法的Python:通过一个可选的命名变量与* ARGS ** kwargs

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) 

编辑:(对我的评论的代码,又不知道这是做的正确的方式,特别是如果有多个键名参数投入自己而不是字典()):

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

你意思就像'__init __(self,custom_name,* args,** kwargs)'? – netcoder 2014-10-10 15:55:34

+0

像__init __(self,custom_name = None,* args,** kwargs),除非您在默认参数之前没有定义的名称。我正在考虑检查'custom_name'是否在** kwargs中,并且如果它从传递给dict的kwargs中删除它,否则将custom_name设置为None。不知道是否有做this.- – user3467349 2014-10-10 15:57:11

回答

2

在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") 
+0

是的,我做了同样的事情,你做的python2方法的标准方法 - 不知道你能做到CUSTOM_NAME =无在python3 ** kwargs之前* ARGS虽然后,将切换对此,谢谢。 – user3467349 2014-10-10 16:06:52