Python 通用接口/C++ 模板等效类型提示
Python typehints for a generic interface / c++ template equivalent
我想在 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
我认为 Generic 是您要查找的内容:
class GenericInterface(Generic[T, S], ABC):
@abstractmethod
def get(self, number: T) -> S:
pass
诚然,我不确定 Generic
或 ABC
是否需要先确认,但你明白了。
我想在 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
我认为 Generic 是您要查找的内容:
class GenericInterface(Generic[T, S], ABC):
@abstractmethod
def get(self, number: T) -> S:
pass
诚然,我不确定 Generic
或 ABC
是否需要先确认,但你明白了。