python使用点操作符访问字典(dict)数据的方法
更新时间:2015年03月16日 15:15:50 作者:八大山人
这篇文章主要介绍了python使用点操作符访问字典(dict)数据的方法,涉及Python操作字典的技巧,需要的朋友可以参考下
本文实例讲述了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']) # bar print(d.foo) # bar d.allowDotting(state=False) print(d['foo']) # bar from https://www.jb51.net print(d.foo) # AttributeError: 'DottableDict' object has no attribute 'foo'
希望本文所述对大家的Python程序设计有所帮助。
相关文章
详解python实现可视化的MD5、sha256哈希加密小工具
这篇文章主要介绍了详解python实现可视化的MD5、sha256哈希加密小工具,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧2020-09-09
最新评论