![](/img/trans.png)
[英]How to set a class method return typing dynamically from a class property
[英]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.