2014-10-10 66 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