繁体   English   中英

"如何将类属性设置为类方法返回类型?"

[英]How to set class property as class method return type?

我有一个 A 类,它有一个类方法并将它的类属性作为返回类型。

A 有一个继承自 A 类的 B 类。

如何在 A 中设置get_instance<\/code>返回类型并通知 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)

通过使类Generic<\/code>对TYPE<\/code>进行参数化<\/em>。 这允许使用相同类型变量引用类属性TYPE<\/code>和返回类型:

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()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM