Accessing dict keys like an attribute?

前端 未结 27 2142
南笙
南笙 2020-11-22 04:22

I find it more convenient to access dict keys as obj.foo instead of obj[\'foo\'], so I wrote this snippet:

class AttributeDict(dict         


        
27条回答
  •  长发绾君心
    2020-11-22 05:13

    class AttrDict(dict):
    
         def __init__(self):
               self.__dict__ = self
    
    if __name__ == '____main__':
    
         d = AttrDict()
         d['ray'] = 'hope'
         d.sun = 'shine'  >>> Now we can use this . notation
         print d['ray']
         print d.sun
    

提交回复
热议问题