我需要知道函数何时被调用,并在调用函数后做一些事情。看来 Interceptor 可以做到。
如何在 python 中使用拦截器?
请您参考如下方法:
这可以使用装饰器来完成:
from functools import wraps
def iterceptor(func):
print('this is executed at function definition time (def my_func)')
@wraps(func)
def wrapper(*args, **kwargs):
print('this is executed before function call')
result = func(*args, **kwargs)
print('this is executed after function call')
return result
return wrapper
@iterceptor
def my_func(n):
print('this is my_func')
print('n =', n)
my_func(4)
输出:
this is executed at function definition time (def my_func)
this is executed before function call
this is my_func
n = 4
this is executed after function call
@iterceptor 将 my_func 替换为 iterceptor 函数的执行结果,即 wrapper 函数。 wrapper 将给定函数包装在一些代码中,通常保留 wrappee 的参数和执行结果,但添加一些额外的行为。
@wraps(func) 用于将函数 func 的签名/文档字符串数据复制到新创建的 wrapper 函数中。
更多信息:
