Accessing dict keys like an attribute?

前端 未结 27 2112
南笙
南笙 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:01

    The easiest way is to define a class let's call it Namespace. which uses the object dict.update() on the dict. Then, the dict will be treated as an object.

    class Namespace(object):
        '''
        helps referencing object in a dictionary as dict.key instead of dict['key']
        '''
        def __init__(self, adict):
            self.__dict__.update(adict)
    
    
    
    Person = Namespace({'name': 'ahmed',
                         'age': 30}) #--> added for edge_cls
    
    
    print(Person.name)
    

提交回复
热议问题