A python class that acts like dict

前端 未结 9 2077

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条回答
  •  旧时难觅i
    2020-11-30 18:27

    This is my best solution. I used this many times.

    class DictLikeClass:
        ...
        def __getitem__(self, key):
            return getattr(self, key)
    
        def __setitem__(self, key, value):
            setattr(self, key, value)
        ...
    

    You can use like:

    >>> d = DictLikeClass()
    >>> d["key"] = "value"
    >>> print(d["key"])
    

提交回复
热议问题