代码

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

 

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2022-02-07
  • 2021-11-08
  • 2022-12-23
  • 2021-11-12
  • 2021-11-13
  • 2021-10-01
猜你喜欢
  • 2022-01-22
  • 2022-12-23
  • 2022-12-23
  • 2021-06-24
  • 2021-08-30
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案