A python class that acts like dict

前端 未结 9 2078

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:34

    I really don't see the right answer to this anywhere

    class MyClass(dict):
        
        def __init__(self, a_property):
            self[a_property] = a_property
    

    All you are really having to do is define your own __init__ - that really is all that there is too it.

    Another example (little more complex):

    class MyClass(dict):
    
        def __init__(self, planet):
            self[planet] = planet
            info = self.do_something_that_returns_a_dict()
            if info:
                for k, v in info.items():
                    self[k] = v
    
        def do_something_that_returns_a_dict(self):
            return {"mercury": "venus", "mars": "jupiter"}
    

    This last example is handy when you want to embed some kind of logic.

    Anyway... in short class GiveYourClassAName(dict) is enough to make your class act like a dict. Any dict operation you do on self will be just like a regular dict.

提交回复
热议问题