इनहेरिटेंस और पॉलिमॉर्फिज़्म के लिए डिज़ाइन

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

Alex Yarosh

Content Quality Analyst @ DataCamp

Polymorphism

 

 

अलग-अलग क्लास के ऑब्जेक्ट्स पर एक ही इंटरफ़ेस से काम करना

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

अकाउंट क्लासों की हाइरार्की

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

ज़रूरी है तो सिर्फ़ इंटरफ़ेस

# Withdraw amount from each of accounts in list_of_accounts
def batch_withdraw(list_of_accounts, amount):
   for acct in list_of_accounts:
      acct.withdraw(amount)

b, c, s = BankAccount(1000), CheckingAccount(2000), SavingsAccount(3000) batch_withdraw([b,c,s]) # <-- Will use BankAccount.withdraw(), # then CheckingAccount.withdraw(), # then SavingsAccount.withdraw()
  • batch_withdraw() को यह जाँचने की ज़रूरत नहीं कि किस ऑब्जेक्ट पर कौन सा withdraw() कॉल करना है
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

Liskov substitution principle

 

बेस क्लास को उसकी किसी भी सबक्लास से बदला जा सके, और प्रोग्राम के गुण न बदलें

जहाँ भी BankAccount काम करता है, वहाँ CheckingAccount भी काम करना चाहिए

बारबरा लिस्कोव का फोटो

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

Liskov substitution principle

 

बेस क्लास को उसकी किसी भी सबक्लास से बदला जा सके, और प्रोग्राम के गुण न बदलें

Syntactically
  • फंक्शन सिग्नेचर संगत हों
    • arguments, returned values
Semantically
  • ऑब्जेक्ट और प्रोग्राम की स्टेट सुसंगत रहे
    • सबक्लास मेथड इनपुट शर्तें सख्त न करे
    • सबक्लास मेथड आउटपुट शर्तें ढीली न करे
    • कोई अतिरिक्त exceptions न हों
Python में ऑब्जेक्ट-ओरिएंटेड प्रोग्रामिंग

LSP का उल्लंघन

Syntactic incompatibility

BankAccount.withdraw() 1 पैरामीटर लेता है, लेकिन CheckingAccount.withdraw() 2 लेता है

Subclass strengthening input conditions

BankAccount.withdraw() कोई भी amount लेता है, लेकिन CheckingAccount.withdraw() मानता है कि amount सीमित है

Subclass weakening output conditions

BankAccount.withdraw() या तो बैलेंस पॉज़िटिव छोड़ता है या error देता है, CheckingAccount.withdraw() बैलेंस नेगेटिव छोड़ सकता है

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

LSP का उल्लंघन

→ सबक्लास के मेथड में अतिरिक्त attributes बदलना

→ सबक्लास के मेथड में अतिरिक्त exceptions फेंकना

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

 

 

 

 

$$\text{\textbf{\Huge{No LSP -- No Inheritance}}}$$

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

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

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

Preparing Video For Download...