I am looking for a way to intercept instance method calls in class MyWrapper
below:
class SomeClass1:
def a1(self):
self.internal_z()
return "a1"
def a2(self):
return "a2"
def internal_z(self):
return "z"
class SomeClass2(SomeClass1):
pass
class MyWrapper(SomeClass2):
# def INTERCEPT_ALL_FUNCTION_CALLS():
# result = Call_Original_Function()
# self.str += result
# return result
def __init__(self):
self.str = ''
def getFinalResult(self):
return self.str
x = MyWrapper()
x.a1()
x.a2()
I want to intercept all function calls make through my wrapper class. In my wrapper class I want to keep track of all the result strings.
result = x.getFinalResult()
print result == 'a1a2'
Some quick and dirty code:
Might not be thorough, but could be a decent starting point, I guess.
What you want to do is quite similar to this question. You should take your example code in the reverse order, i mean creating a class to record return values of method calls, and make the classes you want to watch inherit from it. Which would give something like this
With some minor changes, this method would also allow you to record return values across all RetValWatcher instances.
Edit: added changes suggested by singularity's comment
Edit2: forgot to handle the case where attr is not a method (thx singularity again)
You could wrap your methods with decorators a instanciation time:
Now if you call
hello
orbye
, the call goes throughlog
first: