1.装饰器
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import time 4 def cal(l): 5 start_time=time.time() 6 res=0 7 for i in l: 8 time.sleep(0.1) 9 res+=i 10 stop_time = time.time() 11 print('函数的运行时间是%s' %(stop_time-start_time)) 12 return res 13 14 15 16 print(cal(range(100))) 17 18 19 def index(): 20 pass 21 22 def home(): 23 pass
2.装饰器预演
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import time 4 def timmer(func): 5 def wrapper(*args,**kwargs): 6 start_time=time.time() 7 res=func(*args,**kwargs) 8 stop_time = time.time() 9 print('函数运行时间是%s' %(stop_time-start_time)) 10 return res 11 return wrapper 12 13 def timmer1(func): 14 def wrapper(*args,**kwargs): 15 start_time = time.time() 16 res = func(*args,**kwargs) 17 stop_time = time.time() 18 print('函数运行时间是%s' %(stop_time-start_time)) 19 return res 20 return wrapper() 21 22 23 @timmer 24 def cal(l): 25 res=0 26 for i in l: 27 time.sleep(0.1) 28 res+=i 29 return res 30 31 res=cal(range(20)) 32 print(res) 33 34 35 def index(): 36 pass 37 38 def home(): 39 pass
3.高阶函数
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 ''' 4 高阶函数定义: 5 1.函数接收的参数是一个函数名 6 2.函数的返回值是一个函数名 7 3.满足上述条件任意一个,都可称之为高阶函数 8 ''' 9 # import time 10 # def foo(): 11 # time.sleep(3) 12 # print('你好啊林师傅') 13 14 # def test(func): 15 # # print(func) 16 # start_time=time.time() 17 # func() 18 # stop_time = time.time() 19 # print('函数运行时间是 %s' % (stop_time-start_time)) 20 # foo() 21 # test(foo) 22 23 # def foo(): 24 # print('from the foo') 25 # def test(func): 26 # return func 27 # res=test(foo) 28 # # print(res) 29 # res() 30 31 32 import time 33 def foo(): 34 time.sleep(3) 35 print('来自foo') 36 37 #不修改foo源代码 38 #不修改foo调用方式 39 40 #多运行了一次,不合格 41 # def timer(func): 42 # start_time=time.time() 43 # func() 44 # stop_time = time.time() 45 # print('函数运行时间是 %s' % (stop_time-start_time)) 46 # return func 47 # foo=timer(foo) 48 # foo() 49 50 51 #没有修改被修饰函数的源代码,也没有修改被修饰函数的调用方式,但是也没有为被修饰函数添加新功能 52 # def timer(func): 53 # start_time=time.time() 54 # return func 55 # stop_time = time.time() 56 # print('函数运行时间是 %s' % (stop_time-start_time)) 57 # 58 # foo=timer(foo) 59 # foo() 60
4.函数嵌套
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 # def bar(): 4 # print('from bar') 5 # 6 # def foo(): 7 # print('from foo') 8 # def test(): 9 # pass 10 11 def father(auth_type): 12 # print('from father %s' %name) 13 def son(): 14 # name='linhaifeng_1' 15 # print('我的爸爸是%s' %name) 16 def grandson(): 17 print('我的爷爷是%s' %auth_type) 18 grandson() 19 # print(locals()) 20 son() 21 # father('linhaifeng') 22 father('filedb')
5.加上返回值
1 #!/usr/bin/env python 2 # -*- coding:utf-8 -*- 3 import time 4 def timmer(func): #func=test 5 def wrapper(): 6 start_time=time.time() 7 res=func() #就是在运行test() 8 stop_time = time.time() 9 print('运行时间是%s' %(stop_time-start_time)) 10 return res 11 return wrapper 12 13 @timmer #test=timmer(test) 14 def test(): 15 time.sleep(3) 16 print('test函数运行完毕') 17 return '这是test的返回值' 18 19 # res=test() #就是在运行wrapper 20 # print(res)