首页 > 编程语言 > 详细

Python装饰器进阶

时间:2019-09-21 15:36:41      阅读:82      评论:0      收藏:0      [点我收藏+]

编程的一个原则:
开放封闭原则,对源代码的修改封闭,在源代码不变的情况下,对扩展新功能开放


import time
def foo():
print(‘foo....‘)
time.sleep(2)
def show_time(func):
start = time.time ()
func()
end = time.time ()
print (‘spend %s‘%(end-start))
show_time(foo)

上述代码有个问题。show_time()函数是个基层函数,需要所有上层函数调用它实现功能。。上述功能实现,通过show_time函数调用上层函数实现,不符合逻辑

通过装饰器实现:
def show_time(func):
def inner(): #inner是个闭包函数
start = time.time ()
func()
end = time.time ()
print (‘spend %s‘%(end-start))
return inner
foo=show_time(foo)
foo()
上层函数调用基层函数show_time()函数。

@show_time实现功能一样
import time
def show_time(func):
def inner(): #inner是个闭包函数
start = time.time ()
func()
end = time.time ()
print (‘spend %s‘%(end-start))
return inner
@show_time
def foo():
print(‘foo....‘)
time.sleep(2)
@show_time自动调用后面的函数当参数。相当于 foo=show_time(foo)

Python装饰器进阶

原文:https://www.cnblogs.com/zd37/p/11562150.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!