如何拦截实例方法调用?
我正在寻找一种方法来拦截下面类 MyWrapper
中的实例方法调用:
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()
我想拦截通过我的包装类进行的所有函数调用。在我的包装类中,我想跟踪所有结果字符串。
result = x.getFinalResult()
print result == 'a1a2'
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'
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
一些快速而肮脏的代码:
可能不彻底,但我想可能是一个不错的起点。
Some quick and dirty code:
Might not be thorough, but could be a decent starting point, I guess.
您可以在实例化时间内使用装饰器包装您的方法:
现在,如果您调用
hello
或bye
,则该调用首先会经过log
:You could wrap your methods with decorators a instanciation time:
Now if you call
hello
orbye
, the call goes throughlog
first:您想要做的与这个问题非常相似。
您应该以相反的顺序获取示例代码,我的意思是创建一个类来记录方法调用的返回值,并使您想要观看的类继承它。
这将给出类似这样的内容
通过一些小的更改,此方法还允许您记录所有 RetValWatcher 实例的返回值。
编辑:添加了奇点评论建议的更改
编辑2:忘记处理 attr 不是方法的情况(再次感谢奇点)
编辑3:修复了拼写错误
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)
Edit3: fixed typo