DEV Community

Clean Code Studio
Clean Code Studio

Posted on • Edited on

2

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:

class Rectangle:
def __init__(self, width, height):
self.width = width
self.height = height
def set_width(self, width):
self.width = width
def set_height(self, height):
self.height = height
def get_area(self):
return self.width * self.height
class Square(Rectangle):
def set_width(self, width):
self.width = self.height = width
def set_height(self, height):
self.width = self.height = height
def use_it(rc):
w = rc.width
rc.set_height(10)
assert rc.get_area() == w * 10
rc = Rectangle(2, 3)
use_it(rc)
sq = Square(5)
use_it(sq)

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

Image of Timescale

🚀 pgai Vectorizer: SQLAlchemy and LiteLLM Make Vector Search Simple

We built pgai Vectorizer to simplify embedding management for AI applications—without needing a separate database or complex infrastructure. Since launch, developers have created over 3,000 vectorizers on Timescale Cloud, with many more self-hosted.

Read full post →

Top comments (0)