python泛型
大约 2 分钟
1. 什么是泛型
泛型编程允许我们编写与特定类型无关的代码,提高代码的复用性和类型安全性。在Python中,这主要通过TypeVar来实现,它可以创建类型变量,在函数、类或方法中作为占位符类型使用
TypewVar的作用
- 创建类型变量:定义可以在多个位置使用的通用类型
- 保持类型一致性:确保相关参数或返回值具有相同的类型
- 支持复杂类型约束:可以限制类型变量的可能取值
无约束,可以是任何类型
T = TypeVar('T')
U = TypeVar('U')
V = TypeVar('V')
有约束,只能是指定类型之一
Number = TypeVar('Number', int, float, complex)
有界,必须是指定类型的子类
class Animal(ABC):
@abstractmethod
def speak(self) -> str:
pass
class Dog(Animal):
def speak(self) -> str:
return "Woof!"
class Cat(Animal):
def speak(self) -> str:
return "Meow!"
AnimalType = TypeVar('AnimalType', bound=Animal)
泛型类(Generic Classes)
class Box(Generic[T]):
"""一个泛型容器类"""
def __init__(self, content: T):
self._content = content
def get_content(self) -> T:
return self._content
def set_content(self, new_content: T) -> None:
self._content = new_content
def map(self, func: Callable[[T], U]) -> 'Box[U]':
"""对内容应用函数,返回新的Box"""
return Box(func(self._content))
2. 常见问题
- TypeVar和Union有什么区别
- TypeVar:表示"某个特定但未知的类型",用于保持类型一致性。比如def process(a: T, b: T) -> T确保a、b和返回值是相同类型。
- Union:表示"可以是多种类型中的任何一种",比如Union[int, str]表示可以是int或str,但不要求相关参数类型一致。
- 泛型在运行时还存在吗?Python是如何处理泛型类型信息的?
- Python的泛型主要是静态类型检查工具,在运行时类型信息会被擦除(type erasure)。
Box[int]() == Box[str]() # 在运行时是True