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计算圆周率pi的方法

本文实例讲述了python计算圆周率pi的方法。分享给大家供大家参考。具体如下: from sys import stdout scale = 10000 maxarr = 28...

python使用pygame实现笑脸乒乓球弹珠球游戏

python使用pygame实现笑脸乒乓球弹珠球游戏

今天我们用python和pygame实现一个乒乓球的小游戏,或者叫弹珠球游戏。 笑脸乒乓球游戏功能介绍 乒乓球游戏功能如下: 乒乓球从屏幕上方落下,用鼠标来移动球拍,使其反弹回去,并获得...

python友情链接检查方法

本文实例讲述了python友情链接检查方法。分享给大家供大家参考。具体实现方法如下: # _*_ coding:utf-8 _*_ #xiaohei.python.seo.call....

Python是编译运行的验证方法

虽然Python被说成是一种解释型语言,但是实际上,Python源程序要先经过编译,然后才能运行。 与Java语言类似,Python源程序编译之后得到的是字节码,交由Python虚拟机来...

pytorch 数据处理:定义自己的数据集合实例

数据处理 版本1 #数据处理 import os import torch from torch.utils import data from PIL import Image im...