Nerapake SOLID Prinsip ing Python: Tuladha lan Praktek Paling Apik

Single Responsibility Principle(SRP)

Prinsip iki nyatakake yen saben kelas kudu nduweni tanggung jawab siji. Iku nandheske sing kelas kudu nindakake siji fungsi tartamtu lan ora duwe kakehan alasan kanggo ngganti.

Conto: Ngatur informasi pangguna lan ngirim kabar email.

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)

Prinsip iki nyengkuyung nambah fungsi kanthi nambah kode anyar tinimbang ngowahi kode sing wis ana.

Conto: Nangani macem-macem cara pembayaran ing aplikasi 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)

Prinsip iki negesake manawa obyek saka kelas asale kudu bisa diganti kanggo obyek kelas dasar tanpa mengaruhi akurasi program kasebut.

Tuladha: Ngatur wangun geometris.

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)

Prinsip iki menehi saran supaya antarmuka rusak dadi luwih cilik supaya ora meksa kelas kanggo ngetrapake metode sing ora dibutuhake.

Conto: Antarmuka kanggo nganyari lan nampilake data.

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

Dependency Inversion Principle(DIP)

Prinsip iki nyaranake nggunakake injeksi dependensi kanggo ngatur dependensi.

Conto: Nggunakake injeksi dependensi kanggo ngatur dependensi.

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

Elinga yen ngetrapake SOLID prinsip Python kudu ditindakake kanthi fleksibel adhedhasar tujuan spesifik proyek sampeyan lan pangerten babagan SOLID lan Python.