像dict一样的python类

I want to write a custom class that behaves like dict - so, I am inheriting from dict.

My question, though, is: Do I need to create a private dict member in my __init__() method?. I don't see the point of this, since I already have the dict behavior if I simply inherit from dict.

谁能指出为什么大多数继承片段看起来像下面的片段?

class CustomDictOne(dict):
   def __init__(self):
      self._mydict = {} 

   # other methods follow

而不是简单的...

class CustomDictTwo(dict):
   def __init__(self):
      # initialize my other stuff here ...

   # other methods follow

实际上,我认为我怀疑问题的答案是,用户无法直接访问您的字典(即他们必须使用您提供的访问方法)。

However, what about the array access operator []? How would one implement that? So far, I have not seen an example that shows how to override the [] operator.

So if a [] access function is not provided in the custom class, the inherited base methods will be operating on a different dictionary?

我尝试了以下代码段来测试对Python继承的理解:

class myDict(dict):
    def __init__(self):
        self._dict = {}

    def add(self, id, val):
        self._dict[id] = val


md = myDict()
md.add('id', 123)
print md[id]

我收到以下错误:

KeyError:<内置函数ID>

上面的代码有什么问题?

How do I correct the class myDict so that I can write code like this?

md = myDict()
md['id'] = 123

[编辑]

我已经编辑了上面的代码示例,以摆脱在离开办公桌前犯下的愚蠢错误。这是一个错字(我应该从错误消息中发现它)。

最佳答案

Check the documentation on emulating container types. In your case, the first parameter to add should be self.