Python uses point operators to access Dictionary (dict) data

From , 3 Years ago, written in Python, viewed 52 times.
URL https://pastebin.vip/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

Reply to "Python uses point operators to access Dictionary (dict) data"

Here you can reply to the paste above

captcha

https://burned.cc - Burn After Reading Website