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 Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

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

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay