当我注意到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/