手机
当前位置:查字典教程网 >脚本专栏 >python >python使用点操作符访问字典(dict)数据的方法
python使用点操作符访问字典(dict)数据的方法
摘要:本文实例讲述了python使用点操作符访问字典(dict)数据的方法。分享给大家供大家参考。具体分析如下:平时访问字典使用类似于:dict[...

本文实例讲述了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 http://www.jb51.net print(d.foo) # AttributeError: 'DottableDict' object has no attribute 'foo'

希望本文所述对大家的Python程序设计有所帮助。

【python使用点操作符访问字典(dict)数据的方法】相关文章:

python使用mysqldb连接数据库操作方法示例详解

python爬取网站数据保存使用的方法

Python中字典(dict)和列表(list)的排序方法实例

Python生成随机数的方法

python操作MySQL数据库的方法分享

python生成器的使用方法

python实现问号表达式(?)的方法

python 不关闭控制台的实现方法

python调用shell的方法

python两种遍历字典(dict)的方法比较

精品推荐
分类导航