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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more