การเขียนโปรแกรมเชิงวัตถุใน Python
Alex Yarosh
Content Quality Analyst @ DataCamp

# 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() ตัวไหน
Base class ควรแทนที่ subclass ใดก็ได้โดยไม่เปลี่ยนพฤติกรรมของโปรแกรม
ที่ใดที่ใช้ BankAccount ได้ CheckingAccount ก็ควรใช้ได้เช่นกัน

Base class ควรแทนที่ subclass ใดก็ได้โดยไม่เปลี่ยนพฤติกรรมของโปรแกรม
→ ความไม่เข้ากันด้านไวยากรณ์
BankAccount.withdraw() รับ 1 พารามิเตอร์ แต่ CheckingAccount.withdraw() ต้องการ 2
→ Subclass เพิ่มเงื่อนไข input
BankAccount.withdraw() รับจำนวนเงินใดก็ได้ แต่ CheckingAccount.withdraw() จำกัดจำนวนเงิน
→ Subclass ลดเงื่อนไข output
BankAccount.withdraw() คงยอดเงินเป็นบวกหรือแจ้ง error แต่ CheckingAccount.withdraw() อาจทำให้ยอดเงินติดลบได้
→ การแก้ไข attribute เพิ่มเติมในเมธอดของ subclass
→ การโยน exception เพิ่มเติมในเมธอดของ subclass
$$\text{\textbf{\Huge{No LSP -- No Inheritance}}}$$
การเขียนโปรแกรมเชิงวัตถุใน Python