更改继承方法的类型提示

Change Type Hint of Inherited Method

问题

假设您有一个 class A 和一个子 class B。如果 A 的方法 foo return 是与 B 不同的变量类型,您将如何在没有 re-defining/overriding 方法本身的情况下覆盖方法的类型提示?

现实例子

class RGB:
    def __init__(self, color: Union[tuple[int, int, int], tuple[int, int, int, int]]) -> None:
        self.__color: Union[tuple[int, int, int], tuple[int, int, int, int]] = color
        return

    def __eq__(self, other: Union[RGB, RGBA]) -> bool:
        return isinstance(other, RGB) and self.__color == other.color

    @property
    def color(self) -> tuple[int, int, int]:
        return self.__color


class RGBA(RGB):
    def __init__(self, color: tuple[int, int, int, int]) -> None:
        super().__init__(color)
        return

    @property
    def color(self) -> tuple[int, int, int, int]:
        return self.__color

如您所见,color 属性根据给定颜色是否具有 alpha 值而变化。但是我没有want/need到redefine/overridecolor属性方法,功能没有变化。如何在不覆盖方法的情况下为 color 属性 定义 return 类型提示?

理想情况下,RGBA class 只包含 __init__ 函数。

您可以有一个通用的 Color class 作为 RGBRGBA 的共同父级,由用于表示每个的元组类型参数化。例如,

from typing import Generic, TypeVar


C = TypeVar('C')


class Color(Generic[C]):
    def __init__(self, c: C):
        self.__color = c

    @property
    def color(self) -> C:
        return self.__color


class RGB(Color[tuple[int,int,int]]):
    pass


class RGBA(Color[tuple[int,int,int,int]]):
    pass

这只是一个开始;当您向 class 中添加更多详细信息时,您可能 运行 遇到其他问题。