DEV Community

Clean Code Studio
Clean Code Studio

Posted on • Edited on

3

Python Open Closed Design Pattern (Python SOLID Principles)

The Open/Closed Principle states that a module (such as a class, function, etc.) should be open for extension but closed for modification. In other words, a module should be designed in such a way that it can be easily extended without changing its existing code.

Here's an example in Python:

from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius * self.radius
class Rectangle(Shape):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def calculate_area(shapes):
return sum([shape.area() for shape in shapes])
shapes = [Circle(2), Rectangle(2, 4), Circle(4), Rectangle(4, 8)]
print(f"Total area: {calculate_area(shapes)}")

In this example, the Shape class is an abstract base class that defines the interface for all shapes, and the Circle and Rectangle classes inherit from it and provide concrete implementations of the area method. The calculate_area function takes a list of shapes and calculates the total area by calling the area method on each shape.

By using inheritance and an abstract base class, the existing code can be extended to support new shapes without having to modify the existing code. For example, if we wanted to add a square shape, we could simply create a Square class that inherits from Shapeand provide an implementation of the area method. This adheres to the Open/Closed Principle as the existing code remains closed for modification, while new functionality can be added through extension.

Python
Design Patterns
Clean Code Studio
Python Design Patterns
Python Open Closed Principle Design Pattern
Open Closed Principle (OCP)

Image of Timescale

Timescale – the developer's data platform for modern apps, built on PostgreSQL

Timescale Cloud is PostgreSQL optimized for speed, scale, and performance. Over 3 million IoT, AI, crypto, and dev tool apps are powered by Timescale. Try it free today! No credit card required.

Try free

Top comments (0)