如何在python中应用拦截器 [英] How can Interceptor in python be applied

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

问题描述

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

I need to know when a function is called and do something after calling the function. It seems Interceptor can do it.

如何在python中使用拦截器?

How can I use Interceptor in python ?

推荐答案

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

This can be done using decorators:

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

@iterceptoriterceptor函数(即wrapper函数)的执行结果替换my_func. wrapper将给定的函数包装在某些代码中,通常保留wrappee的参数和执行结果,但是会增加一些其他行为.

@iterceptor replaces my_func with the result of execution of the iterceptor function, that is with wrapper function. wrapper wraps the given function in some code, usually preserving the arguments and execution result of wrappee, but adds some additional behavior.

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

@wraps(func) is there to copy the signature/docstring data of the function func onto the newly created wrapper function.

更多信息:

  • http://python-3-patterns-idioms-test.readthedocs.io/en/latest/PythonDecorators.html
  • https://www.python.org/dev/peps/pep-0318/

这篇关于如何在python中应用拦截器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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