如何在Python中实现类似Scala的参数化泛型类
Python中的参数化类(泛型类)实现方案
Python支持参数化类(即泛型类),需要借助typing模块的TypeVar和Generic来实现,替代你尝试的无效写法。
正确实现代码
from abc import ABC, abstractmethod from typing import TypeVar, Generic, List # 定义类型变量,用于标记泛型参数 NT = TypeVar('NT') class DAGNode(ABC, Generic[NT]): @abstractmethod def dependencies(self) -> List[NT]: pass
Python 3.9+ 简化写法
Python 3.9及以后版本支持直接用内置的list替代typing.List,代码可以更简洁:
from abc import ABC, abstractmethod from typing import TypeVar, Generic NT = TypeVar('NT') class DAGNode(ABC, Generic[NT]): @abstractmethod def dependencies(self) -> list[NT]: pass
子类实现示例
你可以创建指定具体类型的子类:
class IntDAGNode(DAGNode[int]): def dependencies(self) -> list[int]: return [1, 2, 3] class StrDAGNode(DAGNode[str]): def dependencies(self) -> list[str]: return ["node_a", "node_b"]
为什么之前的写法无效
- 直接在类中定义
ntype = int并用于类型注解时,Python会将ntype视为普通变量而非类型标记,无法实现参数化效果。 - Scala风格的
class DAGNode[ntype]语法并非Python的原生语法,Python不支持这种写法。
内容的提问来源于stack exchange,提问作者WestCoastProjects
相关产品推荐
相关产品推荐

