装饰器前奏3(2017年8月29日 16:10:36)
高阶函数+嵌套函数=装饰器
高阶函数
满足以下两个条件就可以叫高阶函数:
1、把一个函数名当作实参传给另外一个函数。(在不修改被装饰的函数源代码的情况下为其添加功能。)
# def bar(): # print('in the bar') # # def test1(func): # print(func) # # test1(bar) # <function bar at 0x0201E270> #--------------------------------------- # def bar(): # print('in the bar') # # def test1(func): # print(func) # func() # test1(bar) #<function bar at 0x0203E270> # #in the bar #--------------------------------------- import time def bar(): time.sleep(3) print('in the bar') def test1(func): start_time=time.time() func() #run bar stop_time=time.time() print("the func run time is %s" %(stop_time-start_time)) test1(bar) #in the bar #the func run time is 3.000171422958374
2、返回值中包含函数名。(不修改函数的调用方式)
import time def bar(): time.sleep(3) print('in the bar') def test2(func): print(func) return func #print(test2(bar)) #<function bar at 0x0202E270> <function bar at 0x0202E270> #test2(bar()) #in the bar None #加小括号相当于把bar的返回值传给他了 bar=test2(bar) #test2+新功能 bar() #run bar #<function bar at 0x019EE270> 停顿3秒 in the bar