PHP前端开发

Python装饰器的执行过程实例分析

百变鹏仔 2小时前 #Python
文章标签 实例

这篇文章主要介绍了python装饰器的执行过程,结合实例形式分析了python装饰器的原理、执行过程及相关操作注意事项,需要的朋友可以参考下

本文实例分析了Python装饰器的执行过程。分享给大家供大家参考,具体如下:

今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭包的执行过程了。其实加上几句话以后就可以很容易的发现,思路给读者,最好自己总结一下,有助于理解。通过代码来说吧。

第一种,装饰器本身不传参数,相对来说过程相对简单的

#!/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>call in_deccall fun观察这几组数据以后,其实很容易发现,先执行装饰器,执行过装饰器以后,代码继续执行最后的print和fun()语句,但是此时的fun函数其实是指向in_dec的,并不是@下面的fun函数,所以接下来执行的是in_dec,在in_dec中有一个fun()语句,遇到这个以后才是执行@后面的fun()函数的。'''</type>

第二种,装饰器本身传参数,个人认为相对复杂,这个过程最好自己总结,有问题大家一块探讨

立即学习“Python免费学习笔记(深入)”;

#!/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>call wrappercall factorialcall factorial() in 0.000000 ms3628800'''</type>