Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # -*- coding: utf-8 -*-
- from copy import copy
- class FlexibleObject(object):
- """Dictionary with getters and setters"""
- def __init__(self, data=None):
- if data is None:
- data = {}
- self._dict = data
- def __getattr__(self, key):
- val = self._dict.get(key, None)
- if isinstance(val, dict):
- return FlexibleObject(val)
- if not val:
- self._dict[key] = {}
- return FlexibleObject(self._dict[key])
- return val
- def update(self, data):
- self._dict.update(data)
- def __setattr__(self, key, value):
- if key == '_dict':
- self.__dict__[key] = value
- else:
- self.__dict__['_dict'][key] = value
- def __add__(self, other):
- if not isinstance(other, FlexibleObject):
- raise
- _new = copy(self._dict)
- _new.update(other.dict)
- return FlexibleObject(_new)
- def __contains__(self, item):
- return item in self._dict
- def keys(self):
- return self._dict.keys()
- @property
- def dict(self):
- return self._dict
- def __repr__(self):
- return str(self._dict)
- a = FlexibleObject()
- b = FlexibleObject()
- a.b.c.d.e.f.g.h.i.j.k = "a"
- b.c.d.e.f.g.h.i.j.k = "b"
- c = a + b
- print(a)
- print(b)
- print(c)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement