【发布时间】:2020-11-13 07:33:28
【问题描述】:
背景:我正在使用 PyCharm 2019.1 和 Python 3.7
问题:我想创建一个泛型抽象类,这样当我从它继承并将泛型类型设置为具体类型时,我希望继承的方法能够识别具体类型并且如果类型不匹配,则显示警告。
带有子类的通用 ABC
from abc import ABC, abstractmethod
from typing import TypeVar, Generic
T = TypeVar("T")
class FooGenericAbstract(ABC, Generic[T]):
@abstractmethod
def func(self) -> T:
pass
class Foo(FooGenericAbstract[dict]): # I am specifying T as type dict
def func(self) -> dict: # I would like the return type to show a warning, if the type is incorrect
pass
错误类型没有警告
我预计这里会出错,因为返回类型 list 与具体类型参数 dict 不匹配。
class Foo(FooGenericAbstract[dict]): # I am specifying T as type dict
def func(self) -> list: # Should be a warning here!
pass
【问题讨论】:
标签: python generics inheritance abstract-class