我需要创建一个特殊的字典子类。 在其中,我想为一组键设置默认值。
我似乎无法找到正确的语法来执行此操作。
这是我一直在尝试的:
class NewDict(dict):
Key1 = "stuff"
Key2 = "Other stuff"
NoList = []
Nada = None
然后我实例化一个这样的对象:
PrefilledDict = NewDict()
并尝试在其中使用某些东西:
print PrefilledDict['Key1']
但似乎我的字典不是字典。
我错过了什么点?
你可以实现你想要的:
class NewDict(dict):
def __init__(self):
self['Key1'] = 'stuff'
...
PrefilledDict = NewDict()
print PrefilledDict['Key1']
使用您的代码,您正在创建 NewDict 类的属性,而不是字典中的键,这意味着您将按以下方式访问属性:
PrefilledDict = NewDict()
print PrefilledDict.Key1
不需要子类化:
def predefined_dict(**kwargs):
d = {
'key1': 'stuff',
...
}
d.update(kwargs)
return d
new_dict = predefined_dict()
print new_dict['key1']
或只是:
defaults = {'a':1, 'b':2}
new_dict = defaults.copy()
print new_dict['a']
@astynax提供了一个很好的答案,但如果你必须使用子类,你可以:
class defaultattrdict(dict):
def __missing__(self, key):
try: return getattr(self, key)
except AttributeError:
raise KeyError(key) #PEP409 from None
然后:
class NewDict(defaultattrdict):
Key1 = "stuff"
Key2 = "Other stuff"
NoList = []
Nada = None
PrefilledDict = NewDict()
print(PrefilledDict['Key1']) # -> "stuff"
print(PrefilledDict.get('Key1')) #NOTE: None as defaultdict
注意:您的代码不遵循 pep8 命名约定。