I don't seem to be able to monkey patch a __call__ method of class instance (and yes, I want to patch just single instances, not all of them).
The following code:
class A(object): def test(self): return "TEST" def __call__(self): return "EXAMPLE" a = A() print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) a.__call__ = lambda : "example" a.test = lambda : "test" print("call method: {0}".format(a.__call__)) print("test method: {0}".format(a.test)) print(a()) print("Explicit call: {0}".format(a.__call__())) print(a.test()) Outputs this:
call method: <bound method A.__call__ of <__main__.A object at 0x7f3f2d60b6a0>> test method: <bound method A.test of <__main__.A object at 0x7f3f2d60b6a0>> call method: <function <lambda> at 0x7f3f2ef4ef28> test method: <function <lambda> at 0x7f3f2d5f8f28> EXAMPLE Explicit call: example test While I'd like it to output:
... example Explicit call: example test How do I monkeypatch __call__()? Why I can't patch it the same way as I patch other methods?
While this answer tells how to do it (supposedly, I haven't tested it yet), it doesn't explain the why part of the question.