我想用一组预定义的有效键实现两个不同的字典。此外,一本字典包含另一本。
class Otherdict (dict):
_keys = ['A','B']
def __init__(self):
for key in self._keys:
self[key] = None
def populateDict(self):
self['B'] = 10
self['A'] = 12
class MyDict(dict):
_keys = ['R','ED']
def __init__(self):
for key in self._keys:
self[key] = None
def __getitem__(self, key):
if key not in self._keys:
raise Exception("'" + key + "'" + " is not a valid key")
dict.__getitem__(self,key)
def __setitem__(self, key, value):
if key not in self._keys:
raise Exception("'" + key + "'" + " is not a valid key")
dict.__setitem__(self,key,value)
def populateDict(self):
d = Otherdict()
d.populateDict()
self['R'] = 3
self['ED'] = d
a = MyDict()
a.populateDict()
print a['ED'].__class__ #prints <type 'NoneType'>
问题是由于某种原因我无法访问位于“ED”键下的字典。我在这里做错了什么?
我还注意到,如果我删除该__getitem__()
方法,代码可以正常工作