Single Responsibility Principle(SRP)
Kanuni hii inasema kwamba kila darasa linapaswa kuwa na jukumu moja. Inasisitiza kwamba darasa linapaswa kufanya kazi moja maalum na lisiwe na sababu nyingi za kubadilika.
Mfano: Kusimamia maelezo ya mtumiaji na kutuma arifa za barua pepe.
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)
Kanuni hii inahimiza kupanua utendakazi kwa kuongeza msimbo mpya badala ya kurekebisha msimbo uliopo.
Mfano: Kushughulikia mbinu tofauti za malipo katika programu ya biashara ya mtandaoni.
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)
Kanuni hii inadai kuwa vipengee vya darasa linalotokana vinapaswa kubadilishwa kwa vitu vya darasa la msingi bila kuathiri usahihi wa programu.
Mfano: Kusimamia maumbo ya kijiometri.
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)
Kanuni hii inashauri kuvunja miingiliano kuwa ndogo ili kuzuia kulazimisha madarasa kutekeleza njia ambazo hazihitaji.
Mfano: Violesura vya kusasisha na kuonyesha data.
class UpdateableFeature:
@abstractmethod
def update_feature(self):
pass
class DisplayableFeature:
@abstractmethod
def display_feature(self):
pass
Dependency Inversion Principle(DIP)
Kanuni hii inapendekeza kutumia sindano ya utegemezi kudhibiti utegemezi.
Mfano: Kutumia sindano ya utegemezi kudhibiti utegemezi.
class OrderProcessor:
def __init__(self, db_connection, email_service):
self.db_connection = db_connection
self.email_service = email_service
Kumbuka kwamba kutumia SOLID kanuni ndani Python kunapaswa kufanywa kwa urahisi kulingana na madhumuni mahususi ya mradi wako na uelewa wako wa SOLID na Python.