Don't like ads? PRO users don't see any ads ;-)
Guest

Untitled

By: a guest on Jun 17th, 2012  |  syntax: None  |  size: 0.73 KB  |  hits: 14  |  expires: Never
download  |  raw  |  embed  |  report abuse  |  print
Text below is selected. Please press Ctrl+C to copy to your clipboard. (⌘+C on Mac)
  1. Monkey patch __del__ to new function
  2. class Test:
  3.     def __str__(self):
  4.         return "Test"
  5.  
  6. def p(self):
  7.     print(str(self))
  8.  
  9. def monkey(x):
  10.     x.__class__.__del__=p
  11.  
  12. a=Test()
  13. monkey(a)
  14. del a
  15.        
  16. def override(p, methods):
  17.     oldType = type(p)
  18.     newType = type(oldType.__name__ + "_Override", (oldType,), methods)
  19.     p.__class__ = newType
  20.  
  21.  
  22. class Test(object):
  23.     def __str__(self):
  24.         return "Test"
  25.  
  26. def p(self):
  27.     print(str(self))
  28.  
  29. def monkey(x):
  30.     override(x, {"__del__": p})
  31.  
  32. a=Test()
  33. b=Test()
  34. monkey(a)
  35. print "Deleting a:"
  36. del a
  37. print "Deleting b:"
  38. del b
  39.        
  40. def monkey_class(x):
  41.     x.__class__.__del__ = p
  42.  
  43. def monkey_object(x):
  44.     x.__del__ = functools.partial(p, x)
  45.        
  46. >>> x = 7
  47. >>> y = x
  48. >>> del x
  49. >>> print y
  50. 7