挑戰(zhàn)每日打卡python基礎(chǔ)題
come with me !今日練習(xí):如何實現(xiàn)一個裝飾器來記錄函數(shù)的執(zhí)行時間
1、記錄函數(shù)的執(zhí)行時間
import time
def count1():
count = 0
for i in range(10000):
count += i
return count
def cul_time():
start_time = time.time()
count1()
end_time = time.time()
return (end_time - start_time)
print(cul_time())
2、實現(xiàn)一個裝飾器來記錄函數(shù)的執(zhí)行時間
import time
def decorator(func): # 外部函數(shù),接收函數(shù)作為參數(shù)
def wrapper(*args,**kwargs): # 內(nèi)部函數(shù)(閉包),訪問外部函數(shù)的變量
start_time = time.time()
result = func(*args,**kwargs) # 調(diào)用原函數(shù)
end_time = time.time()
print(f'執(zhí)行耗時:{end_time-start_time:.8f}秒')
return result
return wrapper # 返回新函數(shù)
@decorator # 語法糖
def count1(n):
count = 0
for i in range(n):
count += i
return count
count1(1000)
3、核心知識點
- 裝飾器的核心定義
- 本質(zhì):裝飾器是一個可調(diào)用對象(函數(shù)或類),它接受另一個函數(shù)作為輸入,并在不修改原函數(shù)代碼的情況下,擴展其功能。
- 語法糖:通過 @decorator_name 語法簡化調(diào)用,等價于 func = decorator_name(func)。
裝飾器中的高階函數(shù):
裝飾器本質(zhì)是一個高階函數(shù),因為它接受一個函數(shù)(如 func)作為輸入,并返回另一個函數(shù)(如 wrapper)。裝飾器中的閉包:
裝飾器中的 wrapper 函數(shù)是一個閉包,因為它可以訪問外部函數(shù)(如 decorator)的局部變量(如 func),即使 decorator 已經(jīng)執(zhí)行完畢。