Python中多重装饰器执行顺序(由下至上)

栏目: Python · 发布时间: 8年前

内容简介:Python中多重装饰器执行顺序(由下至上)
 1 def decorator_a(func):#这里是把f作为参数传入
 2     print('Get in decorator_a')
 3 
 4     def inner_a(*args, **kwargs):
 5         print('Get in inner_a')
 6         return func(*args, **kwargs)  #这里调用的是f 最终执行的函数
 7 
 8     return inner_a
 9 
10 
11 def decorator_b(func): #这里是把inner_a 作为参数传入
12     print('Get in decorator_b')
13 
14     def inner_b(*args, **kwargs):
15         print('Get in inner_b')
16         return func(*args, **kwargs)   #这里调用的是inner_a
17 
18     return inner_b  #此时f=inner_b
19 
20 #多重装饰器 相当于函数连锁赋值   注意区别函数和函数调用的区别
21 @decorator_b
22 @decorator_a
23 def f(x):
24     print('Get in f')
25     return x * 2
26 
27 
28 print(f(1))

注:主要代码解释在注释中

引用:

当解释器执行下面这段代码时,实际上按照从下到上的顺序已经依次调用了 decorator_a 和  decorator_b ,这是会输出对应的  Get in decorator_a 和  Get in decorator_b 。 这时候  f 已经相当于  decorator_b 里的  inner_b 。但因为  f 并没有被调用,所以  inner_b 并没有调用,依次类推  inner_b 内部的  inner_a 也没有调用,所以  Get in inner_a 和  Get in inner_b 也不会被输出。

然后最后一行当我们对 f 传入参数1进行调用时,  inner_b 被调用了,它会先打印  Get in inner_b ,然后在  inner_b 内部调用了  inner_a 所以会再打印  Get in inner_a , 然后再  inner_a 内部调用的原来的  f , 并且将结果作为最终的返回。这时候你该知道为什么输出结果会是那样,以及对装饰器执行顺序实际发生了什么有一定了解了吧。

代码来源: https://www.cnblogs.com/nisen/p/6193426.html?utm_source=itdadao&utm_medium=referral


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

Implementing Responsive Design

Implementing Responsive Design

Tim Kadlec / New Riders / 2012-7-31 / GBP 27.99

New devices and platforms emerge daily. Browsers iterate at a remarkable pace. Faced with this volatile landscape we can either struggle for control or we can embrace the inherent flexibility of the w......一起来看看 《Implementing Responsive Design》 这本书的介绍吧!

在线进制转换器
在线进制转换器

各进制数互转换器

Markdown 在线编辑器
Markdown 在线编辑器

Markdown 在线编辑器

HSV CMYK 转换工具
HSV CMYK 转换工具

HSV CMYK互换工具