如何在模块中统一指定Parent类及子类的泛型类型为float?
可行,以下是两种实现方式
方式1:用类型别名统一绑定泛型参数
如果子类数量较多,推荐先定义一个绑定了float的Parent类型别名,让所有子类继承这个别名,避免重复编写Parent[float]:
# my_module.py from typing import TypeAlias from your_module import Parent # 导入泛型父类 # 定义绑定T=float的Parent类型别名 FloatParent: TypeAlias = Parent[float] # 子类直接继承这个别名 class Child1(FloatParent): pass class Child2(FloatParent): pass # 实例化时无需标注泛型参数,类型检查器会自动识别T=float c1 = Child1(3.14) c2 = Child2(2.71)
方式2:子类继承时直接指定泛型参数
如果子类数量较少,也可以在每个子类继承时直接指定Parent[float]:
# my_module.py from your_module import Parent class Child1(Parent[float]): pass class Child2(Parent[float]): pass # 实例化无需额外标注,类型检查器能正确推断类型 c1 = Child1(3.14)
两种方式都能让mypy、pyright等主流类型检查器识别到当前模块内所有Parent子类的泛型参数T统一为float,实例化时无需重复标注。
内容的提问来源于stack exchange,提问作者Rick
相关产品推荐
相关产品推荐

