高階函數也遵循函數即變量的形式
高階函數的形式:
1、把一個函數名當做實參傳給另外一個函數(在不修改被裝飾函數源代碼的情況下爲其添加功能)
如:
def abc():
print('this is abc')
def def(func):
print(func)
def(abc())
====結果=======出來的是一個內存地址
<function agc at 0x00......>
高階函數實例
import time
def bar():
time.sleep(3)
def test1(func):
start_time = time.time()
func()
stop_time = time.time()
print('func run time %s' %(stop_time - start_time ))
test1(bar) #注意bar後面不能加括號,一加括號就不是傳內存地址了,而把bar的返回值傳給test1了,就不是高階函數了
2、返回值中包含函數名(不修改函數的調用方式)
import time
def bar():
time.sleep(3)
print('this is bar)
def test1(func):
start_time = time.time()
func()
stop_time = time.time()
print('func run time %s' %(stop_time - start_time ))
return func
bar = test1(bar)
返回的是一個內存地址