DEV Community

Clean Code Studio
Clean Code Studio

Posted on • Updated on

Liskov's Substitution Principle (Python Design Patterns)

The Liskov Substitution Principle (LSP) states that objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. This means that a subclass should be a subtype of its superclass, and the behavior of the program should remain the same whether we use the superclass or a subclass. Here's an example in Python:


In this example, the Rectangle class defines the behavior for rectangles, and the Square class inherits from it and represents squares. The use_it function uses a rectangle-like object, such as a Rectangle or a Square, to calculate its area. The function calls the set_height method and then asserts that the area is correct.

When we pass a Rectangle object to use_it, it works as expected and the assertion is true. When we pass a Square object to use_it, it also works and the assertion is true, even though the Square class overrides the behavior of the set_width and set_height methods. This means that the Square class is a subtype of the Rectangle class, and objects of the Square class can be used wherever objects of the Rectangle class are expected, without affecting the correctness of the program. This adheres to the Liskov Substitution Principle.

Python
Design Patterns
Clean Code Studio
Python Design Patterns
Python Liskov's Substitution Principle Design Pattern
Liskov Substitution Design Pattern

Top comments (0)