我想对dict进行子类化并设置默认值 [英] I want to subclass dict and set default values
本文介绍了我想对dict进行子类化并设置默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要创建一个特殊的dict子类。在其中我想为一组键设置默认值。
I have a need to create a special subclass of dict. In it I want to set default values for a set of keys.
我似乎没有找到正确的语法来执行此操作。
I seem to be failing in finding the correct syntax to do this.
这是我一直以来尝试:
class NewDict(dict):
Key1 = "stuff"
Key2 = "Other stuff"
NoList = []
Nada = None
然后我实例化一个这样的对象:
I am then instantiating an object like this:
PrefilledDict = NewDict()
并尝试使用其中的东西:
and trying to use something in there:
print PrefilledDict['Key1']
但似乎我的字典不是字典。
But it seems that my dictionary is not a dictionary.
我缺少什么?
推荐答案
你可以实现你想要的:
class NewDict(dict):
def __init__(self):
self['Key1'] = 'stuff'
...
PrefilledDict = NewDict()
print PrefilledDict['Key1']
使用您的代码,您正在创建NewDict类的属性,而不是字典中的键,这意味着您将访问属性:
With your code, you are creating attributes of the NewDict class, not keys in the dictionary, meaning that you would access the attributes as such:
PrefilledDict = NewDict()
print PrefilledDict.Key1
这篇关于我想对dict进行子类化并设置默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文