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

yipeiwu_com5年前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 //www.jb51.net
print(d.foo)
# AttributeError: 'DottableDict' object has no attribute 'foo'

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

相关文章

使用Eclipse如何开发python脚本

使用Eclipse如何开发python脚本

本文为大家分享了Eclipse开发python脚本的具体方法,供大家参考,具体内容如下 一、安装python 1.访问网址,可以看到如下图所示界面 2.点击上图的"Download",...

Python Queue模块详解

Python中,队列是线程间最常用的交换数据的形式。Queue模块是提供队列操作的模块,虽然简单易用,但是不小心的话,还是会出现一些意外。 创建一个“队列”对象 import Queue...

python进行文件对比的方法

python进行文件对比的方法

文件对比是否一致,我们一般采用md5值对比,假如一样,代表文件一致,不一样说明不一致 假如想要详细的对比信息内容,difflib库提供了文件对比的详细信息和结果 1、首先我们查看下md5...

python使用Pandas库提升项目的运行速度过程详解

python使用Pandas库提升项目的运行速度过程详解

前言 如果你从事大数据工作,用Python的Pandas库时会发现很多惊喜。Pandas在数据科学和分析领域扮演越来越重要的角色,尤其是对于从Excel和VBA转向Python的用户。...

Python调用百度根据经纬度查询地址的示例代码

如下所示: def locatebyLatLng(lat, lng, pois=0): ''' 根据经纬度查询地址 ''' items = {'location': str(...