python - Mypy子类中更具体的参数

标签 python type-hinting mypy python-typing

我想声明一个带有抽象方法的基类,该方法具有类型化参数,以便实现类可以为该参数指定更具体的类型,例如:

from abc import ABC, abstractmethod

class Job(ABC):
    pass

class EasyJob(Job):
    pass

class HardJob(Job):
    pass

class Worker(ABC):
    @abstractmethod
    def run(self, job: Job) -> None:
        raise NotImplementedError()

class EasyWorker(Worker):
    def run(self, job: EasyJob) -> None:
        pass

class HardWorker(Worker):
    def run(self, job: HardJob) -> None:
        pass

但是,mypy 对此的提示是可以理解的:

line 14: error: Argument 1 of "run" is incompatible with supertype "Worker"; supertype defines the argument type as "Job"
line 18: error: Argument 1 of "run" is incompatible with supertype "Worker"; supertype defines the argument type as "Job"

Python 有什么方法可以促进这样的结构吗?

最佳答案

您可能想要Bounded Parametric Polymorphism 。另请参阅this section about bounded type variables

Worker中,您想说您的方法run是通用的,因为它采用某种未指定类型的值TTJob的子类型。从 Worker 派生的类然后用 T 替换具体类型:

from abc import ABC, abstractmethod
from typing import Generic, TypeVar


class Job(ABC):
    pass


class EasyJob(Job):
    pass


class HardJob(Job):
    pass

T = TypeVar('T', bound=Job)


class Worker(ABC, Generic[T]):
    @abstractmethod
    def run(self, job: T) -> None:
        raise NotImplementedError()


class EasyWorker(Worker[EasyJob]):
    def run(self, job: EasyJob) -> None:
        pass


class HardWorker(Worker[HardJob]):
    def run(self, job: HardJob) -> None:
        pass

关于python - Mypy子类中更具体的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59072637/

相关文章:

python - numpy.ndarray 的类型提示/注释 (PEP 484)

python 3.6 : Signature of {method} incompatible with super type {Class}

python - 我怎样才能在多个别名上定义一个递归的 Python 类型?

python - Pandas read_csv : ignore trailing lines with empty data

python - 在 OSX 上从 64 位 Python 切换到 32 位 Python 后,Virtualenvs 将无法工作

python - mongodb find 查询返回的结果不一致

python - 为什么 mypy 找不到我的包裹?

python - Bottle 服务器在计算时没有响应

python - 输入提示和@singledispatch : how do I include `Union[...]` in an extensible way?

python - sqlalchemy 模型声明的类型注释