在研發過程中中,將內容過程中經常用到的一些內容段記錄起來,下邊資料是關於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
