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

如何在继承泛型类时固定部分类型实参的值?

实现泛型类的部分类型绑定

要达到你的需求,需要给ChildInt定义一个专属的类型变量,将其绑定到Base的第二个泛型参数上,同时让ChildInt成为泛型类:

import typing as typ

T = typ.TypeVar("T")
X = typ.TypeVar("X")
class Base(typ.Generic[T, X]):
    pass

# 定义ChildInt专属的类型变量,用于接收后续传入的类型参数
XChild = typ.TypeVar("XChild")
# ChildInt继承Generic[XChild]成为泛型类,同时固定Base的第一个参数为int,第二个参数绑定到XChild
class ChildInt(typ.Generic[XChild], Base[int, XChild]):
    pass

class InheritedInt(ChildInt[str]):
    # 此时InheritedInt等价于Base[int, str]
    pass

说明

  • 新增的XChild类型变量负责承接ChildInt被继承时传入的类型参数(比如示例中的str)。
  • ChildInt通过Base[int, XChild]固定了Base的第一个泛型参数为int,第二个参数则由XChild动态接收。
  • 当InheritedInt继承ChildInt[str]时,XChild会被替换为str,最终InheritedInt的类型就等价于Base[int, str]。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 18:25:28