class Test(object):
def __init__(self, store):
assert isinstance(store, dict)
self.store = store
def __getitem__(self, key):
return self.store[key]
I am trying to use this class. In this document , which implements the __getitem__, should be sufficient to use in my class Test. In fact, when I try to do this, it does not tell me that I cannot, but I have a KeyError:
In [10]: a = Test({1:1,2:2})
In [11]: for i in a: print i
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
<ipython-input-11-8c9c9a8afa41> in <module>()
----> 1 for i in a: print i
<ipython-input-9-17212ae08f42> in __getitem__(self, key)
4 self.store = store
5 def __getitem__(self, key):
----> 6 return self.store[key]
7
KeyError: 0
- Do you know where this 0 comes from? (what happens under the hood)
I know I can solve this problem by adding the __iter__ function:
def __iter__(self):
return dict.__iter__(self.store)
- Is this the best way to solve this problem? (I could also inherit from the dict class).
source
share