您的位置:首页 > 编程语言 > Python开发

python使用点操作符访问字典(dict)数据

2013-09-26 08:04 771 查看
平时访问字典使用类似于: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[/code] 代码转自:脚本分享网 http://www.sharejs.com/codes/python/8716
                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: