Python全系列 教程
3567个小节阅读:5930.5k
目录
鸿蒙应用开发
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
【示例】实现函数执行结果缓存和计时的装饰器功能
xxxxxxxxxx
# coding=utf-8
import time
class CacheDecorator():
__cache={}
def __init__(self,func):
self.func = func
def __call__(self, *args, **kwargs):
# 如果缓存中有对应的方法名,则直接返回对应的返回值
if self.func.__name__ in CacheDecorator.__cache:
return CacheDecorator.__cache[self.func.__name__]
# 如果缓存中没有对应的方法名,则进行计算,并将结果缓存
else:
result = self.func(*args,**kwargs)
CacheDecorator.__cache[self.func.__name__] = result
return result
def cost_time(func):
def infunc(*args,**kwargs):
start = time.time()
result = func(*args,**kwargs)
end = time.time()
print(f"耗时:{end-start}")
return result
return infunc
@cost_time
@CacheDecorator
def func1_long_time():
"""模拟耗时较长,每次执行返回结果都一样的情况"""
print("start func1")
time.sleep(3)
print("end func1")
return 999
if __name__ == '__main__':
r1 = func1_long_time()
r2 = func1_long_time()
print(r1)
print(r2)
"""
运行结果:
start func1
end func1
耗时:3.0079846382141113
耗时:0.0
999
999
"""