I want to write a custom class that behaves like a dict - so I inherit from dict .
My question, however, is this: do I need to create a private dict member in my __init__() method? I don't see the point in this, since I already have dict behavior if I just inherit from dict .
Can someone point out why most inheritance fragments look like below?
class CustomDictOne(dict): def __init__(self): self._mydict = {}
Instead of simple ...
class CustomDictTwo(dict): def __init__(self):
In fact, I think I suspect that the answer to the question is that users cannot directly access your dictionary (i.e. they need to use the access methods you provide).
However, what about the array access operator [] ? How to implement this? So far I have not seen an example that shows how to override the [] operator.
So, if the accessor function [] not provided in the user class, will the inherited base methods work in another dictionary?
I tried the following snippet to test my understanding of Python inheritance:
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]
I got the following error:
KeyError: <built-in id function>
What is wrong with the code above?
How do I fix the myDict class myDict that I can write such code?
md = myDict() md['id'] = 123
[change]
I edited the above code example to get rid of the stupid mistake I made before I left my desk. It was a typo (I should have noticed it from the error message).