通过为dict添加__setattr__
和__getattr__
, 可以属性的语法访问dict的元素
http://www.2cto.com/kf/201507/413971.html
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'], ...)