问题
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.
Here is what I have been trying:
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.
What little bit am I missing?
回答1:
You can achieve what you want as such:
class NewDict(dict):
def __init__(self):
self['Key1'] = 'stuff'
...
PrefilledDict = NewDict()
print PrefilledDict['Key1']
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
回答2:
No subclassing needed:
def predefined_dict(**kwargs):
d = {
'key1': 'stuff',
...
}
d.update(kwargs)
return d
new_dict = predefined_dict()
print new_dict['key1']
or just:
defaults = {'a':1, 'b':2}
new_dict = defaults.copy()
print new_dict['a']
回答3:
@astynax provided a good answer but if you must use a subclass you could:
class defaultattrdict(dict):
def __missing__(self, key):
try: return getattr(self, key)
except AttributeError:
raise KeyError(key) #PEP409 from None
Then:
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
Note: your code doesn't follow pep8 naming convention.
来源:https://stackoverflow.com/questions/10901048/i-want-to-subclass-dict-and-set-default-values