I got a class A who has a class method and take it's class property as return type.
# 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> .
This allows to refer to the class attribute
TYPE<\/code> and the return type with the same type variable:
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()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.