装饰器:
1 import time 2 def cal(l): 3 start_time=time.time() 4 res=0 5 for i in l: 6 time.sleep(0.1) 7 res+=i 8 stop_time = time.time() 9 print('函数的运行时间是%s' %(stop_time-start_time)) 10 return res 11 12 print(cal(range(100)))
装饰器预演:
1 import time 2 def timmer(func): 3 def wrapper(*args,**kwargs): 4 start_time=time.time() 5 res=func(*args,**kwargs) 6 stop_time = time.time() 7 print('函数运行时间是%s' %(stop_time-start_time)) 8 return res 9 return wrapper 10 @timmer 11 def cal(l): 12 res=0 13 for i in l: 14 time.sleep(0.1) 15 res+=i 16 return res 17 18 res=cal(range(10)) 19 print(res)
高阶函数:
1.函数接收的参数是一个函数名
2.函数的返回值是一个函数名
3.满足上述条件任意一个,都可称之为高阶函数
1 例1: 2 import time 3 def foo(): 4 time.sleep(1) 5 print('你好啊玉哥') 6 7 def tests(func): 8 start_time = time.time() 9 func() 10 stop_time = time.time() 11 print('函数运行时间是%s'%(stop_time-start_time)) 12 # foo() 13 tests(foo)
1 例2: 2 def foo1(): 3 print('from the foo1') 4 def test(func): 5 return func 6 7 ress = test(foo1) 8 ress()
1 foo1 = test(foo1) 2 foo1()
函数嵌套:
1 def father1(auth_type): 2 def son(): 3 def grandson(): 4 print('我的爷爷是%s'%auth_type) 5 grandson() 6 son() 7 father1('sqy')