首页 > 解决方案 > 将python泛型传递给父类?

问题描述

我有一个声明为泛型的父类,一个抽象子类和该子类的具体实现,它声明了泛型类型:

MyType = TypeVar('MyType')

class A(Generic[MyType]):
   a: MyType

class B(Generic[MyType], A[MyType]):
   pass

class C(B[int]):
   pass

但这不会将泛型声明从 C 转发到 A,因此 a 的类型不是 int。有没有正确的方法来做到这一点?尝试搜索 SO 和 python 文档,但找不到任何东西。

标签: python-3.xgenericstype-hinting

解决方案


A你有一个类变量,所以它在类的所有实例之间共享。如果您尝试键入提示 this,那么您在任何时候创建一个新的A.

例如a这里有什么类型:

class A(Generic[MyType]):
   a: MyType

class A1(A[str]):
   pass

class A2(A[int]):
   pass

如果你想代表一个成员变量,A那么你可以这样做:

class A(Generic[MyType]):
    def __init__(self, a: MyType):
        self.val = a


class B(Generic[MyType], A[MyType]):
    def __init__(self, b: MyType):
        A.__init__(self, b)


class C(B[int]):
    def __init__(self, c: int):
        B.__init__(self, c)


class D(B[str]):
    def __init__(self, d: str):
        B.__init__(self, d)

在这里,我们有两个类CD which both have different generics int andstr`,并且类型提示有效,因为我们正在创建具有不同泛型的子类。

希望6个月后这可能会有所帮助:)


推荐阅读