装饰外部(库)功能的正确方法是什么? [英] What is the correct way to decorate an external (library) function?

查看:54
本文介绍了装饰外部(库)功能的正确方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在代码中多次使用一个库函数,该函数测试通过/失败条件并相应地执行不同的代码,但是由于某种原因,所找到的结果没有返回值;我想添加一个装饰器,以便可以在我的代码中调用它.

I'm using a library function several times in my code which tests for a pass/fail condition and executes different code accordingly, but for some reason does not have a return value for the result it finds; I'd like to add this with a decorator so that I can call it in my code.

鉴于我无法编辑源文件,正确的方法是什么?

What is the correct way to do this given that I cannot edit the source file?

我该做些什么:

def test_pass(param1, param2):
    external_function(param1, param2)
    if(...):
        return False
    else:
        return True

还是有一种使用漂亮的@decorator语法的方法?

Or is there a way to use the nice @decorator syntax?

推荐答案

@decorator 装饰的是语法糖;函数对象由 decorator(orig_function)调用返回的内容替换.

Decorating with @decorator is syntactic sugar; the function object is replaced by whatever the decorator(orig_function) call returns.

对于外部函数,您只需要使用编写的包装器即可;您只能在定义原始函数时使用装饰器语法.

For external functions, you'd just use the wrapper you wrote; you'd only use the decorator syntax when defining the original function.

这篇关于装饰外部(库)功能的正确方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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