You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中是否可以创建支持List[int]这类泛型参数的dataclass?

如何创建支持泛型参数的dataclass

完全可以实现,你写的代码是Python 3.12版本新增的泛型类简化语法,不同Python版本的实现方式如下:

Python 3.12 及更高版本

你给出的示例只需要补充必要的导入即可正常使用,类型参数直接写在类名后的方括号中:

from dataclasses import dataclass
from typing import List # Python 3.9+ 也可以直接用内置的list替代List

@dataclass
class PagedResponse[type]:
    data: List[type]
    pages: int

使用时直接在类名后传入你需要的具体类型即可,静态类型检查工具(如Mypy、PyCharm内置检查)会自动校验data字段的元素类型是否匹配:

# 声明元素为int类型的分页响应
int_resp = PagedResponse[int](data=[1, 2, 3], pages=1)
# 声明元素为str类型的分页响应
str_resp = PagedResponse[str](data=["a", "b", "c"], pages=2)

Python 3.11 及更低版本

旧版本Python不支持类名后直接加类型参数的语法,需要配合typing.Generic和TypeVar实现泛型dataclass:

from dataclasses import dataclass
from typing import List, Generic, TypeVar

# 先定义类型变量
T = TypeVar("T")

@dataclass
class PagedResponse(Generic[T]):
    data: List[T]
    pages: int

使用方式和3.12+版本完全一致,同样支持PagedResponse[int]这类带类型参数的写法。

可选:运行时类型校验

默认Python的类型标注只用于静态检查,运行时不会校验实际传入的数据类型。如果需要运行时强制校验,可以新增__post_init__方法实现:

from dataclasses import dataclass
from typing import List, Generic, TypeVar

T = TypeVar("T")

@dataclass
class PagedResponse(Generic[T]):
    data: List[T]
    pages: int
    # 可选参数,传入后会自动校验data的元素类型
    item_type: type = None

    def __post_init__(self):
        if self.item_type is not None:
            for idx, item in enumerate(self.data):
                if not isinstance(item, self.item_type):
                    raise TypeError(f"data第{idx}个元素类型错误,期望{self.item_type},实际得到{type(item)}")

使用示例:

# 传入错误类型会直接抛出运行时异常
resp = PagedResponse[int](data=[1, "2", 3], pages=1, item_type=int)

内容的提问来源于stack exchange,提问作者mjuopperi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 09:36:02