kanryu

immutablize instance sample

Aug 7th, 2011
155
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.50 KB | None | 0 0
  1. # -*- coding: utf-8 -*-
  2. """
  3. immutablize instance sample
  4. """
  5. import operator
  6. import types
  7.  
  8.  
  9.  
  10. class A(object):
  11.     def __init__(self, a, b):
  12.         self.a = a
  13.         self.__b = b
  14.    
  15.     def say(self):
  16.         print self.a,self.__b
  17.    
  18.     def incr(self):
  19.         self.a = self.a + 100
  20.    
  21.     def incr2(self):
  22.         self.incr()
  23.  
  24.  
  25. def frozen_instance(instance):
  26.     def new__(_cls, inst):
  27.         return tuple.__new__(_cls, tuple([inst] + inst.__dict__.values()))
  28.    
  29.     def repr__(self):
  30.         return repr(self[0])
  31.    
  32.     def getattr__(self, name):
  33.         return types.MethodType(self[0].__class__.__dict__[name], self, self[0].__class__)
  34.     klass = instance.__class__
  35.     nlass = type('Frozen'+klass.__name__,(tuple,),
  36.         dict(__new__=new__, __repr__=repr__, __getattr__=getattr__)
  37.     )
  38.     for i,k in enumerate(instance.__dict__.keys()):
  39.         setattr(nlass, k, property(operator.itemgetter(1+i)))
  40.    
  41.     return nlass(instance)
  42.  
  43.  
  44.  
  45.  
  46. if __name__ == '__main__':
  47.    
  48.     a = A(1, "aaa")
  49.     print "[a]"
  50.     a.say()
  51.     frozen_a = frozen_instance(a)
  52.     print "[frozen_a]"
  53.     frozen_a.say()
  54.  
  55.     a.incr()
  56.     a.say()
  57.    
  58.     frozen_a.incr2()
  59.  
  60.  
  61. -----outputs-----
  62. [a]
  63. 1 aaa
  64. [frozen_a]
  65. 1 aaa
  66. 101 aaa
  67. Traceback (most recent call last):
  68.   File "fix.py", line 58, in <module>
  69.     frozen_a.incr2()
  70.   File "fix.py", line 22, in incr2
  71.     self.incr()
  72.   File "fix.py", line 19, in incr
  73.     self.a = self.a + 100
  74. AttributeError: can't set attribute
Advertisement
Add Comment
Please, Sign In to add comment