python自定义字典的扩展类,让字典操作起来更容易的代码
在研发过程中中,将内容过程中经常用到的一些内容段记录起来,下边资料是关于python自定义字典的扩展类,让字典操作起来更容易的内容,希望对大家有所用。
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,nicedict())
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
>>> d
{'foo':{'bar':'a', 'blah':7}}
>>> d.a.b.c.e.e.f.g.h= 11

更多精彩