平时访问字典使用类似于:dict['name']的方式,如果能通过dict.name的方式访问会更方便,下面的代码自定义了一个类提供了这种方法。
#from http://www.sharejs.com
class DottableDict(dict):
def __init__(self, *args, **kwargs):
dict.__init__(self, *args, **kwargs)
self.__dict__ = self
def allowDotting(self, state=True):
if state:
self.__dict__ = self
else:
self.__dict__ = dict()
d = DottableDict()
d.allowDotting()
d.foo = 'bar'
print(d['foo'])
# bar
print(d.foo)
# bar
d.allowDotting(state=False)
print(d['foo'])
# bar from http://www.sharejs.com
print(d.foo)
# AttributeError: 'DottableDict' object has no attribute 'foo'
#该代码片段来自于: http://www.sharejs.com/codes/python/8716
代码转自:
脚本分享网
http://www.sharejs.com/codes/python/8716