首页 > 解决方案 > 通用接口/ 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

标签: pythontemplatesinterfacetyping

解决方案


我认为通用是您正在寻找的:

class GenericInterface(Generic[T, S], ABC):
    @abstractmethod
    def get(self, number: T) -> S:
        pass

诚然,我不确定是否GenericABC需要先确认,但你明白了。


推荐阅读