问题描述
def make_bold(fn):
return lambda : "<b>" + fn() + "</b>"
def make_italic(fn):
return lambda : "<i>" + fn() + "</i>"
@make_bold
@make_italic
def hello():
return "hello world"
helloHTML = hello()
输出:< b< i>你好世界< / i< / ; / b>
在大多数示例中,我大致了解装饰器及其如何与装饰器一起使用。
I roughly understand about decorators and how it works with one of it in most examples.
在此示例中,有2个。从输出中可以看出,首先执行 @make_italic
,然后执行 @make_bold
。
In this example, there are 2 of it. From the output, it seems that @make_italic
executes first, then @make_bold
.
这是否意味着对于装饰函数,它将首先运行该函数,然后移至其他装饰器的顶部?先像 @make_italic
,然后是 @make_bold
,而不是相反。
Does this mean that for decorated functions, it will first run the function first then moving towards to the top for other decorators? Like @make_italic
first then @make_bold
, instead of the opposite.
这意味着它与大多数编程语言中的自顶向下方法的规范不同吗?仅用于这种装饰器吗?还是我错了?
So this means that it is different from the norm of top-down approach in most programming lang? Just for this case of decorator? Or am I wrong?
推荐答案
装饰器包装他们正在装饰的功能。因此, make_bold
装饰了 make_italic
装饰器的结果,该装饰器装饰了 hello
函数。
Decorators wrap the function they are decorating. So make_bold
decorated the result of the make_italic
decorator, which decorated the hello
function.
@decorator
语法实际上只是语法糖。以下内容:
The @decorator
syntax is really just syntactic sugar; the following:
@decorator
def decorated_function():
# ...
实际执行为:
def decorated_function():
# ...
decorated_function = decorator(decorated_function)
用返回的任何 decorator()
替换原始的 decorated_function
对象。
replacing the original decorated_function
object with whatever decorator()
returned.
堆叠装饰器重复该过程向外。
Stacking decorators repeats that process outward.
所以您的示例:
@make_bold
@make_italic
def hello():
return "hello world"
可以扩展为:
def hello():
return "hello world"
hello = make_bold(make_italic(hello))
现在调用 hello()
时,您正在调用 make_bold()
返回的对象,真的。 make_bold()
返回一个 lambda
,调用函数 make_bold
包装,这是 make_italic()
的返回值,也是返回原始 hello()
的lambda 。扩展所有这些调用,您将得到:
When you call hello()
now, you are calling the object returned by make_bold()
, really. make_bold()
returned a lambda
that calls the function make_bold
wrapped, which is the return value of make_italic()
, which is also a lambda that calls the original hello()
. Expanding all these calls you get:
hello() = lambda : "<b>" + fn() + "</b>" # where fn() ->
lambda : "<i>" + fn() + "</i>" # where fn() ->
return "hello world"
因此输出变为:
"<b>" + ("<i>" + ("hello world") + "</i>") + "</b>"
这篇关于装饰器执行顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!