本文摘自php中文网,作者不言,侵删。
这篇文章主要介绍了Python装饰器的执行过程,结合实例形式分析了Python装饰器的原理、执行过程及相关操作注意事项,需要的朋友可以参考下本文实例分析了Python装饰器的执行过程。分享给大家供大家参考,具体如下:
今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭包的执行过程了。其实加上几句话以后就可以很容易的发现,思路给读者,最好自己总结一下,有助于理解。通过代码来说吧。
第一种,装饰器本身不传参数,相对来说过程相对简单的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | def dec(fun):
print ( "call dec" )
def in_dec():
print ( "call in_dec" )
fun()
return in_dec
@dec
def fun():
print ( "call fun" )
print ( type (fun))
fun()
|
第二种,装饰器本身传参数,个人认为相对复杂,这个过程最好自己总结,有问题大家一块探讨
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import time, functools
def 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( 10 ))
|
相关推荐:
Python装饰器原理与用法分析
以上就是Python装饰器的执行过程实例分析的详细内容,更多文章请关注木庄网络博客!!
相关阅读 >>
Python之反转序列详解
windows下Python安装paramiko模块和pycrypto模块
Python可以运行在jvm上吗
Python有split函数吗
如何删除Python字典中的元素?如何清空字典?
Python pyqt4实现qq抽屉效果
Python怎么创建文件夹
Python对字符串实现重操作方法讲解
怎么看Python安装了哪些库
Python之spider
更多相关阅读请进入《Python》频道 >>
人民邮电出版社
python入门书籍,非常畅销,超高好评,python官方公认好书。
转载请注明出处:木庄网络博客 » Python装饰器的执行过程实例分析