fastapi_library/test_generic.py
2025-06-05 18:09:51 +08:00

27 lines
635 B
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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)))