Inheritance से फ़ंक्शनैलिटी कस्टमाइज़ करना

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

Alex Yarosh

Content Quality Analyst @ DataCamp

खातों की एक हाइरार्की

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

अब तक क्या है

class BankAccount:
    def __init__(self, balance):
       self.balance = balance

    def withdraw(self, amount):
       self.balance -=amount

# Empty class inherited from BankAccount
class SavingsAccount(BankAccount):
    pass
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

कंस्ट्रक्टर कस्टमाइज़ करना

class SavingsAccount(BankAccount):    

    # Constructor specifically for SavingsAccount with an additional parameter
    def __init__(self, balance, interest_rate):  

# Call the parent constructor using ClassName.__init__() BankAccount.__init__(self, balance) # <--- self is a SavingsAccount but also a BankAccount
# Add more functionality self.interest_rate = interest_rate
  • Parent.__init__(self, args...) से पहले parent का constructor चलाएँ
  • और फ़ंक्शनैलिटी जोड़ें
  • parent constructor कॉल करना अनिवार्य नहीं है
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

कस्टमाइज़्ड कंस्ट्रक्टर से ऑब्जेक्ट बनाएँ

# Construct the object using the new constructor
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

फ़ंक्शनैलिटी जोड़ना

  • सामान्य तरह से मेथड जोड़ें
  • parent और child दोनों क्लास का डेटा उपयोग कर सकते हैं
class SavingsAccount(BankAccount):    

  def __init__(self, balance, interest_rate): 
     BankAccount.__init__(self, balance) 
     self.interest_rate = interest_rate

  # New functionality
  def compute_interest(self, n_periods = 1):
     return self.balance * ( (1 + self.interest_rate) ** n_periods - 1)

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

खातों की एक हाइरार्की

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

फ़ंक्शनैलिटी कस्टमाइज़ करना

class CheckingAccount(BankAccount):

def __init__(self, balance, limit): BankAccount.__init__(self, balance) self.limit = limit
def deposit(self, amount): self.balance += amount
def withdraw(self, amount, fee=0):
if fee <= self.limit: BankAccount.withdraw(self, amount + fee) else: BankAccount.withdraw(self, amount + self.limit)
  • सिग्नेचर बदल सकते हैं (पैरामीटर जोड़ें)
  • parent क्लास का मेथड कॉल करने के लिए Parent.method(self, args...) उपयोग करें
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग
check_acct = CheckingAccount(1000, 25)

# Will call withdraw from CheckingAccount
check_acct.withdraw(200)
# Will call withdraw from CheckingAccount
check_acct.withdraw(200, fee=15)
bank_acct = BankAccount(1000)

# Will call withdraw from BankAccount
bank_acct.withdraw(200)
# Will produce an error
bank_acct.withdraw(200, fee=15)
TypeError: withdraw() got an unexpected
 keyword argument 'fee'
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

अभ्यास करते हैं!

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

Preparing Video For Download...