装饰功能完成后,如何让Python装饰器运行?

雨果·罗杰·布朗(Hugo Rodger-Brown):

我想使用装饰器来处理各种功能的审核(主要是Django视图功能,但不是排他性的)。为此,我希望能够对函数执行后的内容进行审核-即该函数正常运行,并且如果返回的结果没有异常,则装饰器记录该事实。

就像是:

@audit_action(action='did something')
def do_something(*args, **kwargs):
    if args[0] == 'foo':
        return 'bar'
    else:
        return 'baz'

audit_action函数完成后才在哪里运行。

马丁·彼得斯(Martijn Pieters):

装饰器通常返回包装函数。只需在调用包装函数后将逻辑放入包装函数即可。

def audit_action(action):
    def decorator_func(func):
        def wrapper_func(*args, **kwargs):
            # Invoke the wrapped function first
            retval = func(*args, **kwargs)
            # Now do something here with retval and/or action
            print('In wrapper_func, handling action {!r} after wrapped function returned {!r}'.format(action, retval))
            return retval
        return wrapper_func
    return decorator_func

所以audit_action(action='did something')是一个装饰工厂,返回一个范围的decorator_func,这是用来装饰你的do_somethingdo_something = decorator_func(do_something))。

装饰后,您的do_something引用已替换为wrapper_func调用将wrapper_func()导致原始对象do_something()被调用,然后包装函数中的代码可以执行操作。

上面的代码与您的示例函数结合在一起,给出以下输出:

>>> do_something('foo')
In wrapper_func, handling action 'did something' after wrapped function returned 'bar'
'bar'

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章