如何在python中应用拦截器

时间:2018-06-19 13:39:49

标签: python interceptor

我需要知道何时调用函数,并在调用函数后执行一些操作。拦截器似乎可以做到。

如何在python中使用拦截器?

1 个答案:

答案 0 :(得分:1)

这可以使用装饰器来完成:

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将给定的函数包装在一些代码中,通常保留wrappee的参数和执行结果,但是会增加一些其他行为。

wrapper可以将函数@wraps(func)的签名/文档字符串数据复制到新创建的func函数中。

更多信息: