脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python使用点操作符访问字典(dict)数据的方法

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

2019-12-07 20:36八大山人 Python

这篇文章主要介绍了python使用点操作符访问字典(dict)数据的方法,涉及Python操作字典的技巧,需要的朋友可以参考下

本文实例讲述了python使用点操作符访问字典(dict)数据的方法。分享给大家供大家参考。具体分析如下:

平时访问字典使用类似于:dict['name']的方式,如果能通过dict.name的方式访问会更方便,下面的代码自定义了一个类提供了这种方法。

  1. class DottableDict(dict): 
  2.   def __init__(self, *args, **kwargs): 
  3.     dict.__init__(self, *args, **kwargs) 
  4.     self.__dict__ = self 
  5.   def allowDotting(self, state=True): 
  6.     if state: 
  7.       self.__dict__ = self 
  8.     else
  9.       self.__dict__ = dict() 
  10. d = DottableDict() 
  11. d.allowDotting() 
  12. d.foo = 'bar' 
  13. print(d['foo']) 
  14. # bar 
  15. print(d.foo) 
  16. # bar 
  17. d.allowDotting(state=False) 
  18. print(d['foo']) 
  19. # bar from //www.tuohang.net 
  20. print(d.foo) 
  21. # AttributeError: 'DottableDict' object has no attribute 'foo' 

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

延伸 · 阅读

精彩推荐