Python 中泛型的使用
Python 中如何使用泛型(Generic)?请用代码示例说明 TypeVar 和 Generic 的用法。
回答
小字辈
泛型允许定义在类型上参数化的类和函数。
from typing import TypeVar, Generic, List
T = TypeVar('T')
# 泛型函数
def first(items: List[T]) -> T:
return items[0]
print(first([1, 2, 3])) # int
print(first(['a', 'b'])) # str
# 泛型类
class Stack(Generic[T]):
def __init__(self) -> None:
self.items: List[T] = []
def push(self, item: T) -> None:
self.items.append(item)
def pop(self) -> T:
return self.items.pop()
int_stack = Stack[int]()
int_stack.push(1)
int_stack.push(2)
print(int_stack.pop()) # 2
约束泛型:
NumT = TypeVar('NumT', int, float) # 只能是 int 或 float
BoundsT = TypeVar('BoundsT', bound=Comparable) # 必须是 Comparable 的子类
Python 3.12+ 引入更简洁的语法:
def first[T](items: list[T]) -> T: ... # Python 3.12+
class Stack[T]: ... # Python 3.12+