如何拦截实例方法调用? [英] How to intercept instance method calls?

查看:133
本文介绍了如何拦截实例方法调用?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种拦截下面的类 MyWrapper 中的实例方法调用的方法:

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:

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.

这篇关于如何拦截实例方法调用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆