[英]What is the proper way to extend the Dict class?
I want to implement two different dictionaries with a predefined set of valid keys. 我想用一组预定义的有效键实现两个不同的字典。 Also, one dictionary contains the other.
另外,一个字典包含另一个字典。
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'>
The problem is that for some reason I cannot access the dictionary located under the 'ED' key. 问题是由于某种原因,我无法访问“ ED”键下的字典。 What am I doing wrong here?
我在这里做错了什么?
I've also noticed that if I remove the __getitem__()
method, the code works properly 我还注意到,如果删除
__getitem__()
方法,代码将正常运行
__getitem__
must return a value: __getitem__
必须返回一个值:
def __getitem__(self, key):
if key not in self._keys:
raise Exception("'" + key + "'" + " is not a valid key")
return dict.__getitem__(self,key)
If there is no explicit return statement, Python functions return None by default. 如果没有显式的return语句,则Python函数默认返回None。
Use return
in def __getitem__(self, key)
: return dict.__getitem__(self,key)
, 在
def __getitem__(self, key)
使用return
: return dict.__getitem__(self,key)
,
the code runs properly when you remove __getitem__
it's because it then accesses __getitem__
from parent classes(which is dict
in this case). 当您删除
__getitem__
时,代码可以正常运行,这是因为它随后从父类访问__getitem__
(在这种情况下为dict
)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.