有一个抽象类:
class Parent(Generic[T]):
@abstractmethod
def test(self) -> List[T]: ...
我需要创建一个抽象子类,它在方法中将test返回一个包含子类的列表V(例如[Cls1, Cls2, Cls3, ...]):
V = TypeVar("V")
class Child(Parent[V]):
@abstractmethod
def test(self) -> List[V]: ...
这样稍后我就可以指定将返回什么类型的子类test:
class IntChild(Child[int]): # test должен возвращать список подклассов int
我尝试过的:
如果bound你传入它type,它将V被指定为后代类type(即元类),这不适合我
如果Child.test你写in ,那么方法类型与父方法( B , a in )def test(self) -> List[Type[V]]: ...不匹配,这也不好:Child List[Type[V]]Parent List[V]
error: Return type "list[type[V]]" of "test" incompatible with return type "list[V]" in supertype "Parent" [override]
问题:如何指示方法test不应Child返回类型的对象列表V,而是子类列表V
如果我理解正确,那么您需要返回 type[V],而不是 V。那么是什么阻止您指定它呢?
例如,这不会对我造成警告: