Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
460 views
in Technique[技术] by (71.8m points)

python - How to intercept instance method calls?

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'
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Some quick and dirty code:

class Wrapper:
    def __init__(self, obj):
        self.obj = obj
        self.callable_results = []

    def __getattr__(self, attr):
        print("Getting {0}.{1}".format(type(self.obj).__name__, attr))
        ret = getattr(self.obj, attr)
        if hasattr(ret, "__call__"):
            return self.FunctionWrapper(self, ret)
        return ret

    class FunctionWrapper:
        def __init__(self, parent, callable):
            self.parent = parent
            self.callable = callable

        def __call__(self, *args, **kwargs):
            print("Calling {0}.{1}".format(
                  type(self.parent.obj).__name__, self.callable.__name__))
            ret = self.callable(*args, **kwargs)
            self.parent.callable_results.append(ret)
            return ret

class A:
    def __init__(self, val): self.val = val
    def getval(self): return self.val

w = Wrapper(A(10))
print(w.val)
w.getval()
print(w.callable_results)

Might not be thorough, but could be a decent starting point, I guess.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...