I know that in Python it's possible to add at runtime a method to a class:
class Test: def __init__(self): self.a=5 test=Test() import types def foo(self): print self.a test.foo = types.MethodType(foo, test) test.foo() #prints 5 And I also know that it's possible to override the default setattr in the class definition:
class Test: def __init__(self): self.a=5 def __setattr__(self,name,value): print "Possibility disabled for the sake of this test" test=Test() #prints the message from the custom method called inside __init__ However, it seems it's not possible to override at runtime the setattr:
class Test: def __init__(self): self.a=5 test=Test() import types def __setattr__(self,name,value): print "Possibility disabled for the sake of this test" test.__setattr__ = types.MethodType(__setattr__, test) test.a=10 #does the assignment instead of calling the custom method In both the two last cases, dir(test) reports also the method setattr. However, while in the first case it works correctly, in the second it doesn't. Note that I can also call it explicitly, and in that case it works. Seems like that, while the method has been defined, it has not been mapped correctly to override the default assigment method. Am I missing something?
I am using Python 2.7 by the way. The question is mostly academic, since it's probably not a good idea to do such a thing from the program design point of view, but still it deserves an answer - and despite I searched, I wasn't able to find it documented anywhere.