python装饰器和包装器 [英] python decorators and wrappers
问题描述
我很难抓住装饰器,最初我以为装饰器是语法糖,可以执行以下操作:
I am having a hard time grasping decorators, I initially thought decorators were syntactic sugar to do an operation such as:
def decorator(x):
return x*2
@decorator
def plusone(x):
return x+1
print plusone(5)
# would print twelve, because: decorator(plusone(5)) as I have seen
# in some tutorials
但是我注意到必须先在装饰器中创建包装函数。
but I've noticed that a wrapper function needs to be created in the decorator first.
为什么需要返回一个函数,而不是整数?
Why do we need to return a function, not an integer?
推荐答案
(Python)修饰符是函数修改函数的语法糖,
A (Python) decorator is syntactic sugar for a function modifying a function, causing the latter function to act like a modified version of itself.
让我们从一个简单的例子开始(不是很好)。假设我们写了
Let's start with a simple (and not so good) example. Say we write
def double_me(f):
return lambda x: 2 * f(x)
它接受一个带有一个参数的函数,并返回一个带有一个参数的函数,并返回原始函数返回值的两倍。然后我们可以这样使用它:
which takes a function taking one parameter, and returns a function taking one parameter and returning double what the original function would return. Then we can use it like this:
def double_the_add_one(x):
return x + 1
double_the_add_one = double_me(double_the_add_one)
>>> double_the_add_one(1)
4
请注意,我们首先定义了 double_the_add_one
,然后修改 double_the_add_one
并将其绑定回 double_the_add_one
。因此,现在它只是其本身的修改版本-它会执行其最初的操作,然后将结果加倍。装饰者只是简单地使它更加简洁:
Note that we first defined double_the_add_one
, then modified double_the_add_one
and bound it back to double_the_add_one
. So now it is just a modified version of itself - it does what it would do originally, then just doubles the result. Decorators simply make this a bit more succinct:
@double_me
def double_the_add_one(x):
return x + 1
>>> double_the_add_one(1)
4
注意上面的装饰器不是那么好:
Note that the above decorator wasn't that great:
-
它假定有一个位置参数。
It assumed there was a single positional argument.
假定没有关键字参数。
如果修饰的函数具有文档字符串,则该文件将被破坏。
If the decorated function had a docstring, it was clobbered.
您可能应该使用 functools.wraps
实际使用那里的文档中的示例编写装饰器。
You should probably use functools.wraps
to actually write decorators using the example in the docs there.
这篇关于python装饰器和包装器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!