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

Python में Object-Oriented Programming परिचय

George Boorman

Curriculum Manager, DataCamp

बैंक अकाउंट क्लासेस की एक हायरार्की

Python में Object-Oriented Programming परिचय

अब तक क्या है

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 में Object-Oriented Programming परिचय

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

class SavingsAccount(BankAccount):    
    # Constructor for SavingsAccount with an additional argument
    def __init__(self, balance, interest_rate):  

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

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

# Construct the object using the new constructor
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Python में Object-Oriented Programming परिचय

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

  • सामान्य रूप से मेथड जोड़ें
  • पैरेंट और चाइल्ड दोनों क्लास का डेटा इस्तेमाल कर सकते हैं
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 में Object-Oriented Programming परिचय

बैंक अकाउंट क्लासेस की एक हायरार्की

Python में Object-Oriented Programming परिचय

दूसरा चाइल्ड क्लास जोड़ना

class CheckingAccount(BankAccount):

def __init__(self, balance, limit): BankAccount.__init__(self, balance) # Call the ParentClass constructor self.limit = limit
def deposit(self, amount): self.balance += amount
def withdraw(self, amount, fee=0): # New fee argument
if amount <= self.limit: BankAccount.withdraw(self, amount + fee) else: pass # Won't run if the condition isn't met
Python में Object-Oriented Programming परिचय
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 में Object-Oriented Programming परिचय

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

Python में Object-Oriented Programming परिचय

Preparing Video For Download...