问题遇到的现象和发生背景
问题相关代码,请勿粘贴截图
#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 cost_long_time():
'''模拟耗时较长,每次执行返回结果都一样的情况'''
print("start!")
time.sleep(3)
print('end')
return 999
if __name__ == '__main__':
r1=cost_long_time()
r2=cost_long_time()
print(r1)
print(r2)
运行结果及报错内容
C:\Users\黄佳文\AppData\Local\Microsoft\WindowsApps\python3.10.exe D:/pythonProject/pythonProject/pythonProject/pythonProject/装饰器/装饰器/05_缓存和计时装饰器练习.py
Traceback (most recent call last):
File "D:\pythonProject\pythonProject\pythonProject\pythonProject\装饰器\装饰器\05_缓存和计时装饰器练习.py", line 42, in <module>
r1=cost_long_time()
File "D:\pythonProject\pythonProject\pythonProject\pythonProject\装饰器\装饰器\05_缓存和计时装饰器练习.py", line 26, in infunc
result=func(args,**kwargs)
File "D:\pythonProject\pythonProject\pythonProject\pythonProject\装饰器\装饰器\05_缓存和计时装饰器练习.py", line 18, in __call__
result=self.func(*args,**kwargs)
TypeError: cost_long_time() takes 0 positional arguments but 1 was given
进程已结束,退出代码1
我的解答思路和尝试过的方法
我想要达到的结果