这篇文章翻译自activecode的文章Wrist Friend Dictionary
这篇文章属于简书专题Python Recipe
这个字典让你可以更加简单的创建嵌套型数据结构,比如可以:
window.style.width = 5
或者可以:
window['background-color'].rgb = (255, 255, 255)
代码如下:
class easyaccessdict(dict):
def __getattr__(self, name):
if name in self:
return self[name]
n = easyaccessdict()
super().__setitem__(name, n)
return n
def __getitem__(self, name):
if name not in self:
super().__setitem__(name, easyaccessdict())
return super().__getitem__(name)
def __setattr__(self, name, value):
super().__setitem__(name, value)
示例:
>>> d = easyaccessdict()
>>> d
{}
>>> d.foo.bar = 'a'
>>> d
{'foo': {'bar': 'a'}}
>>> d['foo']
{'bar': 'a'}
>>> d['foo'].blah = 7
{'foo': {'bar': 'a', 'blah': 7}}
>>> # 甚至还可以这样
>>> d.a.b.c.e.e.f.g.h= 11
另外可以使用__missing__()
来简化上面的代码实现(collections.defaultdict
就是这样实现的):
class easyaccessdict(dict):
def __getattr__(self, name):
return self[name]
def __setattr__(self, name, value):
super().__setitem__(name,value)
def __missing__(self, name):
super().__setitem__(name, easyaccessdict())
return super().__getitem__(name)