How to intercept instance method calls?

后端 未结 3 1777
孤街浪徒
孤街浪徒 2020-12-08 11:47

I am looking for a way to intercept instance method calls in class MyWrapper below:

class SomeClass1:
    def a1(self):
        self.internal_z         


        
3条回答
  •  轮回少年
    2020-12-08 12:40

    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.

提交回复
热议问题