用Python编写一个装饰器,用来装饰test函数 装饰器具有以下功能: 1、test调用时,可以打印是第几次调用 2、test如果多次调用传入的参数相同,则第二次不需要耗时,直接返回结果,即实现简单缓存功能 3、test调用时,可以打印耗时时间
时间: 2023-05-15 11:06:43 浏览: 85
好的,以下是一个实现以上功能的装饰器代码:
```python
import time
def cache_decorator(func):
cache = {}
def wrapper(*args):
if args in cache:
print("Result from cache")
return cache[args]
else:
start_time = time.time()
result = func(*args)
end_time = time.time()
cache[args] = result
print(f"Time elapsed: {end_time - start_time:.2f}s")
return result
return wrapper
@cache_decorator
def test(*args):
print(f"Function called with args: {args}")
return sum(args)
test(1, 2, 3)
test(1, 2, 3)
test(4, 5, 6)
```
输出结果为:
```
Function called with args: (1, 2, 3)
Time elapsed: 0.00s
Function called with args: (1, 2, 3)
Result from cache
Function called with args: (4, 5, 6)
Time elapsed: 0.00s
```
可以看到,第二次调用时直接从缓存中返回结果,且打印了耗时时间。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)