字典以属性的方式访问

代码

# 字典以属性的方式访问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)

 

posted @ 2022-01-27 18:28  豆浆D  阅读(218)  评论(0编辑  收藏  举报