title: A python class that acts like dict
body: <p>I want to write a custom class that behaves like <code>dict</code> - so, I am inheriting from <code>dict</code>.</p>
  
  <p>My question, though, is: Do I need to create a private <code>dict</code> member in my <code>__init__()</code> method?. I don't see the point of this, since I already have the <code>dict</code> behavior if I simply inherit from <code>dict</code>.</p>
  
  <p>Can anyone point out why most of the inheritance snippets look like the one below?</p>
  
  <pre><code>class CustomDictOne(dict):
     def __init__(self):
        self._mydict = {} 
  
     # other methods follow
  </code></pre>
  
  <p>Instead of the simpler...</p>
  
  <pre><code>class CustomDictTwo(dict):
     def __init__(self):
        # initialize my other stuff here ...
  
     # other methods follow
  </code></pre>
  
  <p>Actually, I think I suspect the answer to the question is so that users cannot directly access your dictionary (i.e. they have to use the access methods that you have provided).</p>
  
  <p>However, what about the array access operator <code>[]</code>? How would one implement that? So far, I have not seen an example that shows how to override the <code>[]</code> operator. </p>
  
  <p>So if a <code>[]</code> access function is not provided in the custom class, the inherited base methods will be operating on a different dictionary?</p>
  
  <p>I tried the following snippet to test out my understanding of Python inheritance:</p>
  
  <pre><code>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]
  </code></pre>
  
  <p>I got the following error:</p>
  
  <blockquote>
    <p>KeyError:  &lt; built-in function id></p>
  </blockquote>
  
  <p>What is wrong with the code above?</p>
  
  <p>How do I correct the class <code>myDict</code> so that I can write code like this?</p>
  
  <pre><code>md = myDict()
  md['id'] = 123
  </code></pre>
  
  <p><strong>[Edit]</strong></p>
  
  <p>I have edited the code sample above to get rid of the silly error I made before I dashed away from my desk. It was a typo (I should have spotted it from the error message).</p>