如何在继承泛型类时固定部分类型实参的值?
实现泛型类的部分类型绑定
要达到你的需求,需要给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
相关产品推荐
相关产品推荐

