平时访问字典使用类似于:dict[‘name’]的方式,如果能通过dict.name的方式访问会更方便,下面的代码自定义了一个类提供了这种方法。
#from http://www.75271.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.75271.com print(d.foo) # AttributeError: 'DottableDict' object has no attribute 'foo'