我想子类化dict并设置默认值

时间:2012-06-05 16:23:17

标签: python dictionary subclass

我需要创建一个特殊的dict子类。在其中我想为一组键设置默认值。

我似乎未能找到正确的语法来执行此操作。

以下是我一直在尝试的内容:

class NewDict(dict):
    Key1 = "stuff"
    Key2 = "Other stuff"
    NoList = []
    Nada = None

然后我实例化一个像这样的对象:

PrefilledDict = NewDict()

并试图在那里使用一些东西:

print PrefilledDict['Key1']

但似乎我的字典不是字典。

我错过了什么?

3 个答案:

答案 0 :(得分:9)

您可以实现您想要的目标:

class NewDict(dict):

    def __init__(self):
        self['Key1'] = 'stuff'
        ...

PrefilledDict = NewDict()
print PrefilledDict['Key1']

使用您的代码,您将创建NewDict类的属性,而不是字典中的键,这意味着您将访问这些属性:

PrefilledDict = NewDict()
print PrefilledDict.Key1

答案 1 :(得分:8)

不需要子类化:

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']

答案 2 :(得分:3)

@astynax provided a good answer但是如果你必须使用子类,你可以:

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命名约定。