Sobes.tech
Senior

What is the principle of the Liskov Substitution Principle (LSP) and how is it applied in Python development?

sobes.tech AI

Answer from AI

The Liskov Substitution Principle (LSP) states that objects of a base (parent) class should be replaceable with objects of a subclass without affecting the correctness of the program. This means that if class B is a subclass of class A, where an object of class A is expected, it is safe to use an object of class B.

Application in Python:

  1. Inheritance without changing behavior: Subclasses should extend functionality, not modify or violate the existing behavior of the base class.

    # Good: Square is a Rectangle where width == height
    class Rectangle:
        def __init__(self, width, height):
            self.width = width
            self.height = height
    
        def area(self):
            return self.width * self.height
    
        def set_width(self, width):
            self.width = width
    
        def set_height(self, height):
            self.height = height
    
    class Square(Rectangle):
        def __init__(self, side):
            super().__init__(side, side)
    
        def set_width(self, width):
            super().set_width(width)
            super().set_height(width)
    
        def set_height(self, height):
            super().set_width(height)
            super().set_height(height)
    
    # Bad: If set_width and set_height in Square are not adapted for Square,
    # the behavior of area() could become illogical when using Square
    # where a Rectangle is expected.
    
  2. Matching method signatures: Methods in subclasses should maintain compatibility with the signatures of methods in the base class (number and types of arguments, return value).

  3. Unexpected exceptions: Subclasses should not throw exceptions that the base class did not declare (if possible in Python, which is less formalized than languages with strict exception typing, but the principle remains).

  4. Preservation of invariants: Subclasses should support the invariants (conditions that must always remain true) of the base class.

Violating LSP often leads to unexpected program behavior and complicates maintenance.