[Python] python使用点操作符访问字典(dict)数据 →→→→→进入此内容的聊天室

来自 , 2020-07-15, 写在 Python, 查看 168 次.
URL http://www.code666.cn/view/af87f7cd
  1. #from http://www.sharejs.com
  2. class DottableDict(dict):
  3.     def __init__(self, *args, **kwargs):
  4.         dict.__init__(self, *args, **kwargs)
  5.         self.__dict__ = self
  6.     def allowDotting(self, state=True):
  7.         if state:
  8.             self.__dict__ = self
  9.         else:
  10.             self.__dict__ = dict()
  11.  
  12. d = DottableDict()
  13. d.allowDotting()
  14. d.foo = 'bar'
  15.  
  16. print(d['foo'])
  17. # bar
  18. print(d.foo)
  19. # bar
  20.  
  21. d.allowDotting(state=False)
  22. print(d['foo'])
  23. # bar from http://www.sharejs.com
  24. print(d.foo)
  25. # AttributeError: 'DottableDict' object has no attribute 'foo'        
  26. #//python/8716

回复 "python使用点操作符访问字典(dict)数据"

这儿你可以回复上面这条便签

captcha