Guest User

Untitled

a guest
Jun 17th, 2019
180
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3. from copy import copy
  4. class FlexibleObject(object):
  5. """Dictionary with getters and setters"""
  6. def __init__(self, data=None):
  7. if data is None:
  8. data = {}
  9. self._dict = data
  10.  
  11. def __getattr__(self, key):
  12. val = self._dict.get(key, None)
  13. if isinstance(val, dict):
  14. return FlexibleObject(val)
  15. if not val:
  16. self._dict[key] = {}
  17. return FlexibleObject(self._dict[key])
  18. return val
  19.  
  20. def update(self, data):
  21. self._dict.update(data)
  22.  
  23. def __setattr__(self, key, value):
  24. if key == '_dict':
  25. self.__dict__[key] = value
  26. else:
  27. self.__dict__['_dict'][key] = value
  28.  
  29. def __add__(self, other):
  30. if not isinstance(other, FlexibleObject):
  31. raise
  32. _new = copy(self._dict)
  33. _new.update(other.dict)
  34. return FlexibleObject(_new)
  35.  
  36. def __contains__(self, item):
  37. return item in self._dict
  38.  
  39. def keys(self):
  40. return self._dict.keys()
  41.  
  42. @property
  43. def dict(self):
  44. return self._dict
  45.  
  46. def __repr__(self):
  47. return str(self._dict)
  48.  
  49.  
  50. a = FlexibleObject()
  51. b = FlexibleObject()
  52. a.b.c.d.e.f.g.h.i.j.k = "a"
  53. b.c.d.e.f.g.h.i.j.k = "b"
  54. c = a + b
  55. print(a)
  56. print(b)
  57. print(c)
RAW Paste Data