装饰器:装饰器由高阶函数和嵌套函数组成,在不修改源代码的情况下(即不修改原来函数的定义和其调用方式),为其他函数添加附加功能,附加的功能写在嵌套函数内。需在被装饰的函数前添加一行---->@装饰器。
例如,用装饰器添加计时功能:
import time
# 定义装饰器,添加计时功能
def timer(func): # timer(test1) func = test1
def deco(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs) # run test1()
stop_time = time.time()
print('the func run time is %s' % (stop_time-start_time))
return deco
# 被装饰函数test1
@timer # test1 = timer(test1)
def test1():
time.sleep(1)
print('in the test1')
# 被装饰函数test2
@timer # test2 = timer(test2) test2(name) = deco(name)
def test2(name):
time.sleep(1)
print('in the test2',name)
# 不改变函数调用方式,增加计数功能
test1()
test2('liming')
运行结果:
in the test1
the func run time is 1.0002362728118896
in the test2 liming
the func run time is 1.00091552734375