Mypy子类中更具体的参数

问题描述 投票:1回答:1

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

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中有什么方法可以促进这种结构?

python typing mypy python-typing
1个回答
1
投票
您可能想要Bounded Parametric Polymorphism。另请参阅this section about bounded type variables

Worker中,您想说您的方法run是通用的,因为它采用某些未指定类型的值T,而T是该方法的子类型工作。从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
© www.soinside.com 2019 - 2024. All rights reserved.