Python की मूल बातें

Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

OOP प्रोग्राम को ऐसे objects के आसपास व्यवस्थित करता है जो state रखते हैं और स्पष्ट interface से behavior देते हैं।

Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग क्या है?

OOP सिस्टम को सहयोग करने वाले objects के रूप में model करता है। हर object state और मान्य operations को जोड़ता है, जिससे बड़े programs में responsibilities स्पष्ट रहती हैं।

OOP के चार मुख्य सिद्धांत

  • Encapsulation: state और behavior को साथ रखकर access नियंत्रित करना।
  • Abstraction: उपयोगी interface दिखाकर अनावश्यक details छिपाना।
  • Inheritance: वास्तविक is-a संबंध में existing class को specialize करना।
  • Polymorphism: अलग objects पर समान operation के साथ उपयुक्त behavior पाना।

उदाहरण की संरचना

  1. BankAccount balance रखता और deposits validate करता है।
  2. SavingsAccount base contract reuse करता है।
  3. SavingsAccount interest के लिए month_end override करता है।
  4. loop सभी accounts को समान interface से चलाता है।
डिज़ाइन सुझाव: जब object केवल दूसरे object का उपयोग करता हो तो composition चुनें; inheritance तभी जब child parent को सही तरह replace कर सके।

बुनियादी उदाहरण

कोड चलाएँ →
main.py
class BankAccount:
    def __init__(self, owner, balance=0):
        self.owner = owner
        self._balance = float(balance)

    @property
    def balance(self):
        return self._balance

    def deposit(self, amount):
        if amount <= 0:
            raise ValueError("Deposit must be positive")
        self._balance += amount

    def month_end(self):
        return "No interest"


class SavingsAccount(BankAccount):
    def __init__(self, owner, balance, interest_rate):
        super().__init__(owner, balance)
        self.interest_rate = interest_rate

    def month_end(self):
        self._balance *= 1 + self.interest_rate
        return "Interest applied"


accounts = [
    BankAccount("Ada", 100),
    SavingsAccount("Lin", 200, 0.05),
]
accounts[0].deposit(50)

for account in accounts:
    status = account.month_end()
    print(f"{account.owner}: {account.balance:.2f} ({status})")

अपेक्षित आउटपुट

Ada: 150.00 (No interest)
Lin: 210.00 (Interest applied)

OOP के चारों सिद्धांत व्यवहार में

ये उदाहरण दिखाते हैं कि Python रोज़मर्रा के code में encapsulation, abstraction, inheritance और polymorphism को कैसे लागू करता है।

Encapsulation

कोड चलाएँ →

state और behavior को साथ रखकर access नियंत्रित करना।

encapsulation.py
class BankAccount:
    def __init__(self, balance=0):
        # Double underscores prevent accidental direct access.
        self.__balance = balance

    @property
    def balance(self):
        # Expose read access without exposing mutation.
        return self.__balance

    def deposit(self, amount):
        # Keep validation next to the state it protects.
        if amount <= 0:
            raise ValueError("Amount must be positive")
        self.__balance += amount


account = BankAccount(100)
account.deposit(50)
print(account.balance)  # 150

Abstraction

कोड चलाएँ →

उपयोगी interface दिखाकर अनावश्यक details छिपाना।

abstraction.py
from abc import ABC, abstractmethod


class PaymentMethod(ABC):
    @abstractmethod
    def pay(self, amount):
        # Callers know what pay does, not how each provider does it.
        pass


class CreditCard(PaymentMethod):
    def pay(self, amount):
        # The concrete class hides its payment implementation.
        return f"Paid ${amount:.2f} by card"


payment = CreditCard()
print(payment.pay(25))

Inheritance

कोड चलाएँ →

वास्तविक is-a संबंध में existing class को specialize करना।

inheritance.py
class Employee:
    def __init__(self, name):
        self.name = name

    def describe(self):
        return self.name


class Developer(Employee):
    def __init__(self, name, language):
        # Reuse initialization from the parent class.
        super().__init__(name)
        self.language = language

    def describe(self):
        # Extend inherited behavior instead of duplicating it.
        return f"{super().describe()} writes {self.language}"


print(Developer("Ada", "Python").describe())

Polymorphism

कोड चलाएँ →

अलग objects पर समान operation के साथ उपयुक्त behavior पाना।

polymorphism.py
class EmailNotification:
    def send(self, message):
        return f"Email: {message}"


class SmsNotification:
    def send(self, message):
        return f"SMS: {message}"


def notify(channels, message):
    for channel in channels:
        # The same call selects behavior from each concrete object.
        print(channel.send(message))


channels = [EmailNotification(), SmsNotification()]
notify(channels, "Order shipped")

यह कैसे काम करता है

BankAccount balance को encapsulate करता है। SavingsAccount interface inherit करके month_end override करता है। loop दोनों objects को समान रूप से उपयोग करता है और Python runtime पर सही method चुनता है।

मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।

अभ्यास के कार्य

बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।

  1. Code चलाने से पहले output का अनुमान लगाएँ।
  2. खाली और गलत input संभालें।
  3. Logic को function में रखें और tests जोड़ें।
Python IDE में चलाएँ →