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.

  1. class ObjectProxy(object):  
  2.     def __init__(self, dictionary=None):  
  3.         if dictionary:  
  4.             for a, b in dictionary.items():  
  5.                 if isinstance(b, (list, tuple)):  
  6.                     setattr(self, a, [ObjectProxy(x)\  
  7.                     if isinstance(x, dict) else x for x in b])  
  8.                 else:  
  9.                     setattr(self, a, ObjectProxy(b)\  
  10.                     if isinstance(b, dict) else b)  
  11.   
  12.     def __repr__(self):  
  13.         return '<objectproxy [%s]="">' % ', '.join(self.__dict__.keys())  
  14.       
  15.     def __getattr__(self, attr):  
  16.         try:  
  17.             return dict.__getattr__(self, attr)  
  18.         except:  
  19.             if not self.__dict__.has_key(attr):  
  20.                 self.__dict__[attr] = ObjectProxy()  
  21.             return self.__dict__[attr]  
  22.           
  23.     def __setattr__(self, attr, value):  
  24.         if self.__dict__.has_key(attr) or '__' in attr:  
  25.             dict.__setattr__(self, attr, value)  
  26.         else:  
  27.             self.__dict__[attr] =  value  
  28.   
  29. a = ObjectProxy()  
  30. a.b.c.d = 3  
  31. a.m.d_ = 2  
  32.   
  33.   
  34. </objectproxy>  

No comments:

Post a Comment