Using a class as a data container

前端 未结 12 1116
孤街浪徒
孤街浪徒 2020-12-02 10:01

Sometimes it makes sense to cluster related data together. I tend to do so with a dict, e.g.,

self.group = dict(a=1, b=2, c=3)
print self.group[\'a\']
         


        
12条回答
  •  佛祖请我去吃肉
    2020-12-02 10:19

    You can combine advantages of dict and class together, using some wrapper class inherited from dict. You do not need to write boilerplate code, and at the same time can use dot notation.

    class ObjDict(dict):
        def __getattr__(self,attr):
            return self[attr]
        def __setattr__(self,attr,value):
            self[attr]=value
    
    self.group = ObjDict(a=1, b=2, c=3)
    print self.group.a
    

提交回复
热议问题