我想用具有类型化参数的抽象方法声明基类,以使实现类可以为该参数指定更具体的类型,例如:
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中有什么方法可以促进这种结构?
在
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