Monkey patch __del__ to new function
问题 For specific debugging purposes I'd like to wrap the del function of an arbitrary object to perform extra tasks like write the last value of the object to a file. Ideally I want to write monkey(x) and it should mean that the final value of x is printed when x is deleted Now I figured that del is a class method. So the following is a start: class Test: def __str__(self): return "Test" def p(self): print(str(self)) def monkey(x): x.__class__.__del__=p a=Test() monkey(a) del a However if I want