一:参考文献
装饰器:https://www.bilibili.com/video/BV11s411V7Dt?spm_id_from=333.337.search-card.all.click
二:定义
装饰器是一个闭包函数,用于拓展原来函数功能的一种函数;
作用:不用更改原函数的代码前提下给函数增加新的功能;
特殊:它的返回值也是一个函数;
使用:将一些特定或者通用的方法写成装饰器,在待装饰函数定义前加上@+装饰器名称;
#带有不定参数的装饰器
import time
def deco(func):
def wrapper(*args, **kwargs):
startTime = time.time()
func(*args, **kwargs)
endTime = time.time()
msecs = (endTime - startTime)*1000
print("time is %d ms" %msecs)
return wrapper
@deco
def func(a,b):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b))
@deco
def func2(a,b,c):
print("hello,here is a func for add :")
time.sleep(1)
print("result is %d" %(a+b+c))
if __name__ == '__main__':
f = func
func2(3,4,5)
f(3,4)
#func()
def dec1(func):
print("1111")
def one():
print("2222")
func()
print("3333")
return one
def dec2(func):
print("aaaa")
def two():
print("bbbb")
func()
print("cccc")
return two
@dec1
@dec2
def test():
print("test test")
test()
输出:
aaaa
1111
2222
bbbb
test test
cccc
3333
分析调用顺序:
- 多个装饰器装饰时,自下而上执行;
- 相当于执行了test=dect1(dect2(test)),此时先执行dect2(test),结果是输出aaaa,return two;即dect1(two);
- print(“1111”) --》 return one --》 print(“2222”) --》执行 func(two)
- print(“bbbb”) --》func() --》print(“test test”) --》 print(“cccc”)
- print(“3333”)