写再前面的话
装饰器就是用于拓展函数功能的一种函数
函数+实参高阶函数+返回值高阶函数+嵌套函数+语法糖=装饰器、
无参装饰器
import time
def deco(func):
def wrapper():
startTime = time.time()
func()
endTime = time.time()
msecs = (endTime - startTime) * 1000
print('time is %d ms' % msecs)`在这里插入代码片`
return wrapper
@deco
def func():
print('hello')
time.sleep(1)
print('world')
带参的装饰器
def deco_p(func):
def wrapper(a, b):
startTime = time.time()
func(a, b)
endTime = time.time()
msecs = (endTime - startTime) * 1000
print("time is %d ms" % msecs)
return wrapper
@deco_p
def func_p(a, b):
print("add:")
time.sleep(1)
print('result is %d' % (a + b))
带有不定参数的装饰器
def deco_pa(func_pa):
def wrapper(*args, **kwargs):
startTime = time.time()
func_pa(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime) * 1000
print('time is %d' % msecs)
return wrapper
@deco_pa
def func_pa(a, b, c):
print('add multi para:')
time.sleep(2)
print('result is %d' % (a + b + c))
多个装饰器的实现
def deco1(func_multi):
def wrapper(*args, **kwargs):
print('this is the first deco:')
startTime = time.time()
func_multi(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime) * 1000
print('the exec time is %d ms' % msecs)
return wrapper
def deco2(func_multi):
def wrapper(*args, **kwargs):
print('this is the second deco:')
func_multi(*args, **kwargs)
print('second deco is here')
return wrapper
@deco1
@deco2
def func_multi(a, b, c, d):
print('multi:')
time.sleep(1)
print('result for multi: %d' % (a * b * c * d))
主函数调用实例
if __name__ == '__main__':
# func()
# f = func
# f()
# func_p(3, 4)
# func_pa(3, 3, 3)
func_multi(1, 2, 3,4)