1 有參數(shù)的裝飾器 --> 高階函數(shù)
創(chuàng)新互聯(lián)公司是一家專(zhuān)注于成都做網(wǎng)站、網(wǎng)站設(shè)計(jì)與策劃設(shè)計(jì),葫蘆島網(wǎng)站建設(shè)哪家好?創(chuàng)新互聯(lián)公司做網(wǎng)站,專(zhuān)注于網(wǎng)站建設(shè)十余年,網(wǎng)設(shè)計(jì)領(lǐng)域的專(zhuān)業(yè)建站公司;建站業(yè)務(wù)涵蓋:葫蘆島等地區(qū)。葫蘆島做網(wǎng)站價(jià)格咨詢(xún):18982081108
2 執(zhí)行時(shí)間 --> time 庫(kù)
上代碼:
from functools import wraps
import time
# 面向?qū)ο髮?xiě)法
class TakeTime:
def __init__(self, para: int):
self.para = para
def __call__(self, func):
@wraps(func)
def wrapped(*args, **kwargs):
start_time = time.time()
name = func.__name__
func(*args, **kwargs)
count_time = time.time() - start_time
if self.para >= count_time:
print("the {name} take {time}, less time".format(name=name, time=count_time))
else:
print("the {name} take {time}, more time".format(name=name, time=count_time))
return func
return wrapped
# 常規(guī)寫(xiě)法
def func_time(para: int):
def decorator(func):
@wraps(func)
def wrapper(*args, **kwargs):
start_time = time.time()
name = func.__name__
func(*args, **kwargs)
count_time = time.time() - start_time
if para >= count_time:
print("the {name} take {time}, less time".format(name=name, time=count_time))
else:
print("the {name} take {time}, more time".format(name=name, time=count_time))
return func
return wrapper
return decorator
@TakeTime(10)
def log():
for x in range(10):
time.sleep(0.5)
@func_time(10)
def log1():
for x in range(10):
time.sleep(0.5)