本文实例讲述了python使用点操作符访问字典(dict)数据的方法。分享给大家供大家参考。具体分析如下:
平时访问字典使用类似于:dict['name']的方式,如果能通过dict.name的方式访问会更方便,下面的代码自定义了一个类提供了这种方法。
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'])# barprint(d.foo)# bard.allowdotting(state=false)print(d['foo'])# bar from http://www.jb51.netprint(d.foo)# attributeerror: 'dottabledict' object has no attribute 'foo'
希望本文所述对大家的python程序设计有所帮助。