我想用一组预定义的有效键实现两个不同的字典。此外,一本字典包含另一本字典。
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__()
方法,代码将正常运行
最佳答案
__getitem__
必须返回一个值:
def __getitem__(self, key):
if key not in self._keys:
raise Exception("'" + key + "'" + " is not a valid key")
return dict.__getitem__(self,key)
如果没有明确的 return 语句,Python 函数默认返回 None。
关于python - 扩展 Dict 类的正确方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11204443/