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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Python中的super用法详解

一、问题的发现与提出 在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的写法如代码段1: 代码段1: 复制代码 代码如下:  c...

浅谈Python中的数据类型

数据类型: float — 浮点数可以精确到小数点后面15位 int — 整型可以无限大 bool — 非零为true,零为false list — 列表 Float/Int: 运...

使用Python编写Prometheus监控的方法

要使用python编写Prometheus监控,需要你先开启Prometheus集群。可以参考/post/148895.htm 安装。在python中实现服务器端。在Prometheus...

python中class的定义及使用教程

类的定义 class classname[(父类名)]: – 成员函数及成员变量 _ init _ 构造函数:初始化对象 _ del_ 析构函数:销毁对象 定义类的成员函数时,必须默认一...

python提取xml里面的链接源码详解

因群里朋友需要提取xml地图里面的链接,就写了这个程序。 代码: #coding=utf-8 import urllib import urllib.request import r...