Python装饰器进阶

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


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)

posted @ 2019-09-21 11:32  七又七分之七  阅读(136)  评论(0)    收藏  举报