python - 通用接口/ C++ 模板等效的 Python 类型提示
问题描述
我想在 python 中有一个通用的类型提示接口。我想要达到的大致如下,但我一直在寻找解决方案:
T = TypeVar('T')
S = TypeVar('S')
class GenericInterface(ABC):
@abstractmethod
def get(self, number: T)->S:
pass
def get_example()->GenericInterface[int, str]:
class Example(GenericInterface[int, str]):
def get(self, number: int)->str:
return str(number)
return Example()
所以在上面的例子中GenericInterface[int, str]
应该描述下面的类型化接口:
class MyInterface(ABC):
@abstractmethod
def get(self, number: int)->str:
pass
解决方案
我认为通用是您正在寻找的:
class GenericInterface(Generic[T, S], ABC):
@abstractmethod
def get(self, number: T) -> S:
pass
诚然,我不确定是否Generic
或ABC
需要先确认,但你明白了。
推荐阅读
- c# - 由于无效的 Web URL,Twitter 创建应用程序失败
- postgresql - 遍历postgresql触发器中的表
- abap - 从 itab 中获取其他字段中每个不同值的最高值
- android - Android模拟器上的白屏,但屏幕截图显示它可以正常工作
- python - 用于过滤 Pandas DataFrame 行的 excel 嵌套 if 条件的 Python 等效项
- python - Python方法之间的区别是否可以创建新变量
- javascript - 使用 API 删除有时有效,有时无效
- url - QnA Maker 管理知识 - 添加新 URL 的问题
- random - 如何在 Jenkinsfile 中为 Selenium 端口分配随机 4 位数字
- html - 模板的表单参数中的值未在视图中传递