【发布时间】:2021-12-27 09:16:03
【问题描述】:
我有一个类 A,它有一个类方法并将它的类属性作为返回类型。
A 得到了一个继承自 A 类的 B 类。
如何在A中设置get_instance返回类型并通知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"
【问题讨论】:
-
cls.TYPE可以更改为任何内容。所以除了Any以外的其他描述都是不正确的,恕我直言。 -
你有一个错字 -
get_instace应该是get_instance -
您是否需要
A成为具有具体TYPE的具体类? -
@VPfB
Any是对的,但是当我调用子类get_instance方法时cls.TYPE是固定的 -
@match 已修复,谢谢
标签: python type-hinting mypy