27 lines
635 B
Python
27 lines
635 B
Python
from typing import Generic, TypeVar, Dict
|
||
from typing import Optional
|
||
|
||
K = TypeVar("K") # 键类型
|
||
V = TypeVar("V") # 值类型
|
||
|
||
class GenericCache(Generic[K, V]):
|
||
def __init__(self):
|
||
self._store: Dict[K, V] = {}
|
||
|
||
def set(self, key: K, value: V) -> None:
|
||
self._store[key] = value
|
||
|
||
def get(self, key: K) -> Optional[V]:
|
||
return self._store.get(key)
|
||
|
||
# 使用示例
|
||
cache = GenericCache[str, int]() # 键为 str,值为 int
|
||
cache.set("count", 100)
|
||
value: Optional[int] = cache.get("count") # 返回 100
|
||
|
||
cache.set(112, "123")
|
||
|
||
|
||
for key in cache._store.keys():
|
||
|
||
print(type(cache.get(key))) |