Aiwatar da SOLID ƙa'idodi a cikin Python: Misalai da Mafi kyawun Ayyuka

Single Responsibility Principle(SRP)

Wannan ka'ida ta bayyana cewa kowane aji yakamata ya kasance yana da alhakin guda ɗaya. Yana jaddada cewa aji ya kamata ya yi takamaiman aiki ɗaya kuma ba shi da dalilai da yawa don canzawa.

Misali: Sarrafa bayanan mai amfani da aika sanarwar imel.

class UserManager:  
    def create_user(self, user_data):  
        # Logic for creating a user  
        pass  
  
class EmailService:  
    def send_email(self, email_data):  
        # Logic for sending an email  
        pass  

Open/Closed Principle(OCP)

Wannan ƙa'ida tana ƙarfafa faɗaɗa ayyuka ta ƙara sabon lamba maimakon canza lambar da ke akwai.

Misali: Karɓar hanyoyin biyan kuɗi daban-daban a cikin aikace-aikacen kasuwancin e-commerce.

from abc import ABC, abstractmethod  
  
class PaymentProcessor(ABC):  
    @abstractmethod  
    def process_payment(self):  
        pass  
  
class CreditCardPaymentProcessor(PaymentProcessor):  
    def process_payment(self):  
        # Logic for processing credit card payment  
        pass  
  
class PayPalPaymentProcessor(PaymentProcessor):  
    def process_payment(self):  
        # Logic for processing PayPal payment  
        pass  

Liskov Substitution Principle(LSP)

Wannan ƙa'ida ta tabbatar da cewa abubuwan da aka samo asali yakamata su kasance a musanya su da abubuwan ajin tushe ba tare da yin tasiri ga daidaiton shirin ba.

Misali: Sarrafar da siffofi na geometric.

class Shape:  
    def area(self):  
        pass  
  
class Rectangle(Shape):  
    def area(self):  
        return self.width * self.height  
  
class Square(Shape):  
    def area(self):  
        return self.side * self.side  

Interface Segregation Principle(ISP)

Wannan ƙa'idar tana ba da shawarar ɓata musaya zuwa ƙanana don guje wa tilasta azuzuwan aiwatar da hanyoyin da ba sa buƙata.

Misali: Interfaces don ɗaukakawa da nuna bayanai.

class UpdateableFeature:  
    @abstractmethod  
    def update_feature(self):  
        pass  
  
class DisplayableFeature:  
    @abstractmethod  
    def display_feature(self):  
        pass  

Dependency Inversion Principle(DIP)

Wannan ƙa'idar tana ba da shawarar yin amfani da allurar dogaro don sarrafa abin dogaro.

Misali: Amfani da allurar dogaro don sarrafa abin dogaro.

class OrderProcessor:  
    def __init__(self, db_connection, email_service):  
        self.db_connection = db_connection  
        self.email_service = email_service  

Ka tuna cewa yin amfani da SOLID ƙa'idodi a cikin Python ya kamata a yi shi cikin sassauƙa bisa takamaiman manufar aikin ku da fahimtar ku SOLID da Python.