我有一個自定義字典類(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
你意思就像'__init __(self,custom_name,* args,** kwargs)'? – netcoder 2014-10-10 15:55:34
像__init __(self,custom_name = None,* args,** kwargs),除非您在默認參數之前沒有定義的名稱。我正在考慮檢查'custom_name'是否在** kwargs中,並且如果它從傳遞給dict的kwargs中刪除它,否則將custom_name設置爲None。不知道是否有做this.- – user3467349 2014-10-10 15:57:11