天天看點

字典以屬性的方式通路

代碼

# 字典以屬性的方式通路1
class AttributeDict(dict): 
    __getattr__ = dict.__getitem__
    __setattr__ = dict.__setitem__

# 字典以屬性的方式通路2
class ObjDict(dict):
    """
    Makes a  dictionary behave like an object,with attribute-style access.
    """
    def __getattr__(self,name):
        try:
            return self[name]
        except:
            raise AttributeError(name)
    def __setattr__(self,name,value):
        self[name]=value      

使用

from util.common import AttributeDict, ObjDict


d1 = {'name':'zhangsan','age':19}
d1 = AttributeDict(d1)

print(d1.name)


d2 = {'name':'zhangsan','age':19}
d2 = ObjDict(d2)

print(d2.name)