装饰器基本理论

装饰器:本质就是函数

功能:为其他函数添加附加功能

原则:1.不修改被修饰函数的源代码

   2.不修改被修饰函数的调用方式

 1 #为函数添加新功能
 2 import time
 3 def timmer(func):      #定义装饰器
 4     def wrapper(*args,**kwargs):
 5         start_time=time.time()
 6         res=func(*args,**kwargs)
 7         stop_time=time.time()
 8         print('函数运行的时间为:%s'%(stop_time-start_time))
 9         return res
10     return wrapper
11 @timmer
12 def cal(l):
13     res = 0
14     for i in l:
15         time.sleep(0.1)
16         res+=i
17     return res
18 res=cal(range(11))
19 print(res)
 1 #为foo添加统计时间的功能
 2 import time
 3 def foo():
 4     time.sleep(3)    #加大foo的运行时间
 5     print('Hello,diudiu')
 6 def test(func):
 7     print(func)
 8     start_time=time.time()
 9     func()
10     stop_time=time.time()
11     print('函数运行的时间是:%s'%(stop_time-start_time))
12 test(foo)    #修改了函数的调用方式

装饰器的知识储备:

装饰器=高阶函数+函数嵌套+闭包

高阶函数

1.函数接受的参数是一个函数名

1 def foo():
2     print('Hello,diudiu')
3 def test(func):
4     print(func)    #func为foo的内存地址
5     func()
6 #运行test
7 test(foo)   #将foo函数名传给了test函数的形参,test为高阶函数

2.函数的返回值是一个函数名

3.满足上述条件任意一个,都可称之为高阶函数

原文地址:https://www.cnblogs.com/hui147258/p/11063914.html