[英]How to set class property as class method return type?
I got a class A who has a class method and take it's class property as return type.我有一个 A 类,它有一个类方法并将它的类属性作为返回类型。
And a got a class B who inherit from class A. A 有一个继承自 A 类的 B 类。
How to set get_instance<\/code> return type in A and to inform B get the right type?
如何在 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)
Parameterise<\/em> over the TYPE<\/code> by making the class
Generic<\/code> .
通过使类
Generic<\/code>对
TYPE<\/code>进行参数化<\/em>。
This allows to refer to the class attribute
TYPE<\/code> and the return type with the same type variable:
这允许使用相同类型变量引用类属性
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.