Mypy 子类中更具体的参数
Mypy more specific parameter in subclass
我想用抽象方法声明一个基础 class,该方法具有类型化参数,以便实现 classes 可以为该参数指定更具体的类型,例如:
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. See also this section about bounded type variables。
在 Worker 中,您想说您的方法 运行 是通用的,因为它需要一个值某些未指定类型 T 而 T 是 Job 的子类型。 类 派生自 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
我想用抽象方法声明一个基础 class,该方法具有类型化参数,以便实现 classes 可以为该参数指定更具体的类型,例如:
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. See also this section about bounded type variables。
在 Worker 中,您想说您的方法 运行 是通用的,因为它需要一个值某些未指定类型 T 而 T 是 Job 的子类型。 类 派生自 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