class ObjectProxy(object):
def __init__(self, dictionary=None):
if dictionary:
for a, b in dictionary.items():
if isinstance(b, (list, tuple)):
setattr(self, a, [ObjectProxy(x)\
if isinstance(x, dict) else x for x in b])
else:
setattr(self, a, ObjectProxy(b)\
if isinstance(b, dict) else b)
def __repr__(self):
return '' % ', '.join(self.__dict__.keys())
def __getattr__(self, attr):
try:
return dict.__getattr__(self, attr)
except:
if not self.__dict__.has_key(attr):
self.__dict__[attr] = ObjectProxy()
return self.__dict__[attr]
def __setattr__(self, attr, value):
if self.__dict__.has_key(attr) or '__' in attr:
dict.__setattr__(self, attr, value)
else:
self.__dict__[attr] = value
a = ObjectProxy()
a.b.c.d = 3
a.m.d_ = 2
27.6.10
Python design pattern series: recursive data structures
I introduce a recursive structure in which you can create and object, and add to it at will.
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment