Sot*_*oto 5 python generics inheritance abstract-class
背景:我使用的是 PyCharm 2019.1 和 Python 3.7
问题:我想创建一个泛型抽象类,这样当我从它继承并将泛型类型设置为具体类型时,我希望继承的方法能够识别具体类型并在类型不匹配时显示警告。
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
Run Code Online (Sandbox Code Playgroud)
我预计这里会出现错误,因为返回类型list与具体类型参数不匹配dict。
class Foo(FooGenericAbstract[dict]): # I am specifying T as type dict
def func(self) -> list: # Should be a warning here!
pass
Run Code Online (Sandbox Code Playgroud)
小智 7
from abc import ABC, abstractmethod
from typing import Dict, Generic, List, TypeVar
T = TypeVar("T")
class FooGenericAbstract(ABC, Generic[T]):
@abstractmethod
def func(self) -> T:
pass
class Foo(FooGenericAbstract[Dict[str, int]]):
def func(self) -> Dict[str, str]:
pass
Run Code Online (Sandbox Code Playgroud)
对于 coc.nvim 和 python 3.8,mypy 0.770 按预期发出警告。
我想也许你应该使用类型提示而不是内置类型,因为 mypy 到目前为止无法识别内置类型。
| 归档时间: |
|
| 查看次数: |
1453 次 |
| 最近记录: |