A python class that acts like dict

前端 未结 9 2060

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 priva

9条回答
  •  情深已故
    2020-11-30 18:23

    The problem with this chunk of code:

    class myDict(dict):
        def __init__(self):
            self._dict = {}
    
        def add(id, val):
            self._dict[id] = val
    
    
    md = myDict()
    md.add('id', 123)
    

    ...is that your 'add' method (...and any method you want to be a member of a class) needs to have an explicit 'self' declared as its first argument, like:

    def add(self, 'id', 23):
    

    To implement the operator overloading to access items by key, look in the docs for the magic methods __getitem__ and __setitem__.

    Note that because Python uses Duck Typing, there may actually be no reason to derive your custom dict class from the language's dict class -- without knowing more about what you're trying to do (e.g, if you need to pass an instance of this class into some code someplace that will break unless isinstance(MyDict(), dict) == True), you may be better off just implementing the API that makes your class sufficiently dict-like and stopping there.

提交回复
热议问题