python - 扩展 Dict 类的正确方法是什么?

标签 python dictionary extend

我想用一组预定义的有效键实现两个不同的字典。此外,一本字典包含另一本字典。

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/

相关文章:

Python list.append 输出值与 list.extend 不同

python - 在 Pandas 中查找一列值在另一列值中的位置的矢量化方法

Python:查找字典元组值的最大值

python - 计算 CSV 中的属性值?

javascript - 如何扩展 MarionetteJS 模块以减少代码重复

actionscript-3 - 如何正确扩展 AS3 Point 类?

python - Pandas 计数跨行的值大于不同列中的另一个值

python - 为什么我使用 Tag.models.all() 后 Taggit (Django-Tag) 就无法工作

python - pd.read_csv 出现奇怪的字母 'u'

python - 合并两个共享相同键值的字典 :Value