[英]Why does my decorator execute the code in this order?
I have the following code and I have a hard time understanding why it prints the statements in the order it does. 我有以下代码,并且很难理解为什么它按顺序打印语句。
def main():
print('1')
registry=[]
def register(func):
print('2')
registry.append(func)
return func
@register
def f1():
print('3')
print('4')
f1()
main()
This code prints: 此代码打印:
1
2
4
3
But I'm wondering why it doesn't print: 但我想知道为什么它不打印:
1
2
3
4
when the @register
is called I understand it that register(f1)
is called, it prints 2
and then f1
is returned. 当
@register
被调用时,我了解到register(f1)
被调用,它会打印2
,然后返回f1
。 To me it seems like 3
should be printed next since f1
is returned. 在我看来,既然返回了
f1
接下来应该打印3
。 But instead f1
is not called until the very end f1()
statement. 而是
f1
不叫,直到最后一刻f1()
语句。 Doesn't return func
run the function it returns? 是否不
return func
运行它返回的函数?
Consider the equivalent code that doesn't use decorator syntax. 考虑不使用装饰器语法的等效代码。 Also, we make
registry
a pre-defined global so that the code actually runs. 另外,我们将
registry
为预定义的全局变量,以便代码实际运行。
registry = []
def main():
print('1')
#registry=[]
def register(func):
print('2')
registry.append(func)
return func
def f1():
print('3')
f1 = register(f1)
print('4')
f1()
main()
The first function that gets called is register
, so the first value output is 2
. 被调用的第一个函数是
register
,因此输出的第一个值是2
。 Next, print('4')
outputs 4
. 接下来,
print('4')
输出4
。 Third, f1
is called and outputs 3
. 第三,调用
f1
并输出3
。 Finally, main
is called and outputs 1
. 最后,调用
main
并输出1
。
register
never calls f1
; register
永不调用 f1
; it simply adds it to the list registry
and returns it. 它只是将其添加到列表
registry
并返回它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.