python 实现缓存
时间: 2023-06-29 18:17:14 浏览: 52
Python 可以通过使用装饰器来实现缓存。下面是一个简单的缓存装饰器实现:
```python
import functools
def cache(func):
memo = {}
@functools.wraps(func)
def wrapper(*args):
if args in memo:
return memo[args]
else:
result = func(*args)
memo[args] = result
return result
return wrapper
```
这个装饰器将函数的结果缓存在一个字典中,并在下一次调用时返回缓存的值。如果函数的参数是可哈希的,那么就可以将它们作为字典的键。这个装饰器可以用于任何可调用对象,包括函数、方法和类。例如:
```python
@cache
def fibonacci(n):
if n < 2:
return n
else:
return fibonacci(n-1) + fibonacci(n-2)
print(fibonacci(10)) # 55
print(fibonacci(20)) # 6765
```
这个例子缓存了 Fibonacci 数列的结果,这样就可以避免重复计算。
相关问题
python 实现本地缓存
Python 实现本地缓存可以使用 Python 标准库中的 `pickle` 模块来实现,具体步骤如下:
1. 导入 pickle 模块。
```python
import pickle
```
2. 定义一个缓存数据的字典。
```python
cache = {}
```
3. 定义一个函数来读取缓存。如果缓存中存在数据,则返回缓存中的数据;否则,从外部数据源获取数据并写入缓存。
```python
def get_data(key):
if key in cache:
return cache[key]
else:
data = fetch_data_from_external_source() # 从外部数据源获取数据
cache[key] = data # 将数据写入缓存
return data
```
4. 定义一个函数来写入缓存。
```python
def set_data(key, value):
cache[key] = value
with open('cache.pickle', 'wb') as f:
pickle.dump(cache, f)
```
5. 定义一个函数来从本地文件中加载缓存。
```python
def load_cache():
try:
with open('cache.pickle', 'rb') as f:
cache = pickle.load(f)
except FileNotFoundError:
pass
```
完整代码示例:
```python
import pickle
cache = {}
def get_data(key):
if key in cache:
return cache[key]
else:
data = fetch_data_from_external_source() # 从外部数据源获取数据
cache[key] = data # 将数据写入缓存
return data
def set_data(key, value):
cache[key] = value
with open('cache.pickle', 'wb') as f:
pickle.dump(cache, f)
def load_cache():
try:
with open('cache.pickle', 'rb') as f:
cache = pickle.load(f)
except FileNotFoundError:
pass
```
python 如何实现缓存
Python 可以使用以下方式实现缓存:
1. 使用 Python 内置的 `lru_cache` 装饰器,将函数的执行结果缓存起来,以减少函数的重复计算。例如:
```python
from functools import lru_cache
@lru_cache(maxsize=None)
def my_func(arg):
# some computation
return result
```
2. 使用 Python 的 `dict` 类型作为缓存容器,以键值对的方式存储函数的输入参数和输出结果。例如:
```python
cache = {}
def my_func(arg):
if arg in cache:
return cache[arg]
else:
result = # some computation
cache[arg] = result
return result
```
3. 使用 Python 的第三方缓存库,例如 `redis`、`memcached` 等,将函数的输入参数作为缓存键,输出结果作为缓存值,以加速函数的执行。例如:
```python
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
def my_func(arg):
cache_key = f'my_cache_{arg}'
if r.exists(cache_key):
return r.get(cache_key)
else:
result = # some computation
r.set(cache_key, result)
return result
```