Advertisement
DeaD_EyE

Silly getattr and setattr for dict.

May 6th, 2016
213
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.40 KB | None | 0 0
  1. import random
  2. from pprint import pprint
  3. class NamedDict(dict):
  4.     def __getattr__(self, attr):
  5.         return self.get(attr)
  6.     def __setattr__(self, attr, value):
  7.         self.update({attr: value})
  8.  
  9.  
  10. ndict = NamedDict()
  11. ndict.x = 10
  12. ndict.y = 25
  13. ndict.val = random.randint(0, 1000)
  14. print('Dicts content:')
  15. pprint(ndict)
  16. print('\n\nDir:')
  17. pprint(dir(ndict))
  18.  
  19. #ndict.5 = 22 wont work
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement