python - 在子类型中使用额外的构造函数参数违反了 LSP 原则

标签 python oop design-patterns solid-principles liskov-substitution-principle

当我注意到this answer时,我一直在阅读里氏替换原理。 。它有一个 Circle 和一个 ColoredCircle 类型,其中 ColoredCircle 的构造函数需要一个额外的参数; 颜色

class Circle:
    radius: int

    def __init__(self, radius: int) -> None:
        self.radius = radius

class ColoredCircle(Circle):
    radius: int
    color: str

    def __init__(self, radius: int, color: str) -> None:
        super().__init__(radius)
        self.color = color

这是否违反了以下要求之一? (taken from this answer)。对于 ColoredCircle 来说,唯一的其他选项是公共(public)变量或 set_color 方法。

Pre-conditions cannot be strengthened: Assume your base class works with a member int. Now your sub-type requires that int to be positive. This is strengthened pre-conditions, and now any code that worked perfectly fine before with negative ints is broken.

如果我在这里搜索的方向错误,请告诉我。另外,如果一个子类型有更多的参数需要处理,通常如何管理这些参数,新的抽象总是必要的吗?

最佳答案

当类 X 具有构造函数时,该构造函数不是类型 X 的对象上的方法。由于它不是 X 类型对象上的方法,因此它也不必作为派生类型对象上的方法存在——它与 LSP 无关。

关于python - 在子类型中使用额外的构造函数参数违反了 LSP 原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71486599/

相关文章:

algorithm - 寻找 bool 选择的算法或设计模式

c# - 将规范模式公开给客户端代码的标准做法?

language-agnostic - 什么时候不应该使用单例模式? (除了显而易见的)

oop - 混合基于构造函数和基于 setter 的注入(inject)是一件坏事吗?

构造函数中的 JavaScript 访问器属性

Python 继承和关键字参数

python - Django 1.8 模板的 URL 标签 TypeError

c# - 私有(private)变量和 setter/getter 的问题

python - 如何创建一个由 kx2 散点图组成的seaborn图,该散点图具有所有类并集的共享图例

python - 属性错误 : 'CrossEntropyLoss' object has no attribute 'backward'