如何将 class 属性 设置为 class 方法 return 类型?

How to set class property as class method return type?

我得到了一个 class A,他有一个 class 方法,并将其 class 属性 作为 return 类型。

A 得到了 class B 继承自 class A.

如何设置get_instance return输入A并通知B得到正确的类型?

# typings.py
from typing import TypeVar, Type

AType = TypeVar("AType", bound="A")

T = TypeVar("T", int, str)


class A:
    TYPE = int

    @classmethod
    def get_instance(cls: Type[AType]) -> "AType.TYPE":
        return cls.TYPE()


class B(A):
    TYPE = str


a = B.get_instance()

reveal_type(a)

mypy typings.py

typings.py:12: error: Name "AType.TYPE" is not defined
typings.py:17: error: Incompatible types in assignment (expression has type "Type[str]", base class "A" defined the type as "Type[int]")
typings.py:22: note: Revealed type is "Any"

通过使 class GenericTYPE 上参数化 。这允许引用 class 属性 TYPE 和具有相同类型变量的 return 类型:

from typing import TypeVar, Type, Generic

T = TypeVar("T", str, int)


class Base(Generic[T]):
    TYPE: Type[T]

    @classmethod
    def get_instance(cls: "Type[Base[T]]") -> "T":
        return cls.TYPE()

请注意,这会阻止直接设置 TYPE。需要单独的通用 Base 和具体 A 定义。

class A(Base[int]):
    TYPE = int

class B(Base[str]):
    TYPE = str