通过为dict添加__setattr__
和__getattr__
, 可以属性的语法访问dict的元素
class Storage(dict): def init(self, *args, **kw): dict.__init__(self, *args, **kw) # 为dict添加属性访问符 def __getattr__(self, key): return self[key] def __setattr__(self, key, value): self[key] = value def __delattr__(self, key): del self[key]if __name__ == '__main__': data = {'name': 'mark', 'age': 18} datasrc=Storage(data) print(datasrc.name, ...) print(datasrc['age'], ...)