[英]Alternative that doesn't violate the Liskov substitution principle
Considering the following structure of classes:考虑以下类的结构:
from abc import ABC, abstractmethod
class ModelSettings(ABC):
...
class BlueModelSettings(ModelSettings):
...
class RedModelSettings(ModelSettings):
...
class Model(ABC):
@abstractmethod
def compute(self, settings: ModelSettings):
...
class BlueModel(Model):
def compute(self, settings: BlueModelSettings):
...
class RedModel(Model):
def compute(self, settings: RedModelSettings):
...
MyPy is complaining that the implementations of compute
in BlueModel
and RedModel
violate the Liskov substitution principle. MyPy 抱怨BlueModel
和RedModel
中的compute
实现违反了 Liskov 替换原则。 I understand this and also understand why it makes sense.我理解这一点,也理解它为什么有意义。
My question is, instead of the above structure, what would be another approach that would satisfy the following requirements:我的问题是,除了上述结构之外,还有什么方法可以满足以下要求:
compute
should receive settings, not apples or oranges基本模型有一个合同, compute
应该接收设置,而不是苹果或橘子In a way, I essentially want that a subclass' method argument is stricter than what its base class stipulates, which goes directly against the Liskov principle.在某种程度上,我本质上希望子类的方法参数比它的基类规定的更严格,这直接违背了 Liskov 原则。 Which is what's telling me there might be a more suitable approach.这就是告诉我可能有更合适的方法。
Note:笔记:
Model
is library code so it can't know of eg BlueModelSettings
which is client code Model
是库代码,因此它不知道例如BlueModelSettings
是客户端代码You need your Model
to be generic in the type of settings
.您需要您的Model
在settings
类型中是通用的。
T = TypeVar('T', bound=ModelSettings)
class Model(ABC, Generic[T]):
@abstractmethod
def compute(self, settings: T):
...
class BlueModel(Model[BlueModelSettings]):
def compute(self, settings: BlueModelSettings):
...
class RedModel(Model[RedModelSettings]):
def compute(self, settings: RedModelSettings):
...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.