python装饰器的执行过程
来源:互联网 发布:淘宝海外代购要身份证 编辑:程序博客网 时间:2024/05/18 21:09
今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭包的执行过程了。其实加上几句话以后就可以很容易的发现,思路给读者,最好自己总结一下,有助于理解。通过代码来说吧。
第一种,装饰器本身不传参数,相对来说过程相对简单的
#!/usr/bin/python#coding: utf-8# 装饰器其实就是对闭包的使用def dec(fun): print("call dec") def in_dec(): print("call in_dec") fun() # 必须加上返回语句,不然的话会默认返回None return in_dec@decdef fun(): print("call fun")# 注意上面的返回语句加上还有不加上的时候这一句执行的区别print(type(fun))fun()'''通过观察输出结果可以知道函数执行的过程call dec<type 'function'>call in_deccall fun 观察这几组数据以后,其实很容易发现,先执行装饰器,执行过装饰器以后,代码继续执行最后的print和fun()语句,但是此时的fun函数其实是指向in_dec的,并不是@下面的fun函数,所以接下来执行的是in_dec,在in_dec中有一个fun()语句,遇到这个以后才是执行@后面的fun()函数的。'''
#!/usr/bin/python#coding: utf-8import time, functoolsdef performance(unit): print("call performance") def log_decrator(f): print("call log_decrator") @functools.wraps(f) def wrapper(*arg, **kw): print("call wrapper") t1 = time.time() t = f(*arg, **kw) t2 = time.time() tt = (t2 - t1) * 1000 if unit == "ms" else (t2 - t1) print 'call %s() in %f %s' % (f.__name__, tt, unit) return t return wrapper return log_decrator@performance("ms")def factorial(n): print("call factorial") return reduce(lambda x, y: x * y, range(1, 1 + n))print(type(factorial))#print(factorial.__name__)print(factorial(10))'''接下来的是输出结果,通过结果其实很容易发现执行的过程call performancecall log_decrator 通过观察前两组的输出结果可以知道,先执行装饰器<type 'function'>call wrappercall factorialcall factorial() in 0.000000 ms3628800'''
0 0
- python装饰器的执行过程
- python中装饰器的执行细节
- python装饰器执行顺序
- python的执行过程
- python的执行过程
- python的执行过程
- python 多重装饰器执行顺序
- Python的装饰器
- python的装饰器
- python的装饰器
- Python的装饰器
- python的装饰器
- Python的装饰器
- python - 装饰器使用过程中的误区
- Python - 装饰器使用过程中的误区
- Python - 装饰器使用过程中的误区
- python程序的执行过程
- python程序的执行过程
- Linux安装openssh详细步骤及遇到问题的解决方案
- 二维码(QR code)基本结构及生成原理
- 算法在计算机中的作用
- 第十二节 shell编写监控脚本
- 《Spring》-----容器的注解
- python装饰器的执行过程
- Learn Java 接口
- BootStrap组件
- 【51单片机学习过程记录】16 中断之 串口中断的应用2(中断方式)
- 微信小程序开发指南,含最新api
- Install TensorFlow(V0.11.0) on Mac OSX (Sierra)
- approximate CBR stream
- ubuntu上建立交叉编译环境,在qemu上运行ARM镜像
- 深入理解javascript原型和闭包(9)——简述【执行上下文】下