简体   繁体   English

如何使用装饰器将 function 的结果包装在多个外部库函数中

[英]How can I use a decorator to wrap the result of my function, inside of a multiple external library functions

I've only recently learned about decorators, and despite reading nearly every search result I can find about this question, I cannot figure this out.我最近才了解装饰器,尽管阅读了我能找到的关于这个问题的几乎所有搜索结果,但我无法弄清楚这一点。 All I want to do is define some function "calc(x,y)", and wrap its result with a series of external functions, without changing anything inside of my function, nor its calls in the script, such as:我要做的就是定义一些 function "calc(x,y)",并用一系列外部函数包装它的结果,而不改变我的 function 内部的任何东西,也不改变它在脚本中的调用,例如:

@tan
@sqrt
def calc(x,y):
    return (x+y)

### calc(x,y) = tan(sqrt(calc(x,y))
### Goal is to have every call of calc in the script automatically nest like that. 

After reading about decorators for almost 10 hours yesterday, I got the strong impression this is what they were used for.在昨天阅读了将近 10 个小时的装饰器后,我得到了强烈的印象,这就是它们的用途。 I do understand that there are various ways to modify how the functions are passed to one another, but I can't find any obvious guide on how to achieve this.我确实知道有多种方法可以修改函数相互传递的方式,但我找不到任何关于如何实现这一点的明显指南。 I read that maybe functools wraps can be used for this purpose, but I cannot figure that out either.我读到也许 functools 包装可以用于此目的,但我也无法弄清楚。

Most of the desire here is to be able to quickly and easily test how different functions modify the results of others, without having to tediously wrap functions between parenthesis... That is, to avoid having to mess with parenthesis at all, having my modifier test functions defined on their own lines.这里的大部分愿望是能够快速轻松地测试不同的函数如何修改其他函数的结果,而不必在括号之间繁琐地包装函数......也就是说,为了避免完全弄乱括号,有我的修饰符在自己的行上定义的测试函数。

A decorator is simply a function that takes a function and returns another function.装饰器只是一个 function,它接受一个 function 并返回另一个 function。

def tan(f):
    import math
    def g(x,y):
        return math.tan(f(x,y))
    return g

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM