การสืบทอดคลาส

การเขียนโปรแกรมเชิงวัตถุใน Python

Alex Yarosh

Content Quality Analyst @ DataCamp

การนำโค้ดกลับมาใช้ใหม่

การเขียนโปรแกรมเชิงวัตถุใน Python

การนำโค้ดกลับมาใช้ใหม่

 

1. มีคนทำไว้แล้ว

 

  • Modules เหมาะกับฟังก์ชันการทำงานที่ตายตัว
  • OOP เหมาะกับการปรับแต่งฟังก์ชันการทำงาน

โลโก้ของแพ็กเกจ Python หลายตัว

การเขียนโปรแกรมเชิงวัตถุใน Python

การนำโค้ดกลับมาใช้ใหม่

 

1. มีคนทำไว้แล้ว

 

2. DRY: Don't Repeat Yourself

องค์ประกอบ GUI ต่างๆ

การเขียนโปรแกรมเชิงวัตถุใน Python

การนำโค้ดกลับมาใช้ใหม่

 

1. มีคนทำไว้แล้ว

 

2. DRY: Don't Repeat Yourself

อย่าใช้องค์ประกอบ GUI ซ้ำ

การเขียนโปรแกรมเชิงวัตถุใน Python

การสืบทอด

 

$$\Large{\text{New class functionality = Old class functionality + extra}}$$

การเขียนโปรแกรมเชิงวัตถุใน Python

คลาส account

การเขียนโปรแกรมเชิงวัตถุใน Python

savings account ที่สืบทอดมาจาก account

การเขียนโปรแกรมเชิงวัตถุใน Python

สองคลาสที่สืบทอดมาจาก account

การเขียนโปรแกรมเชิงวัตถุใน Python

เมธอดที่ถูกแก้ไขใน checking account

การเขียนโปรแกรมเชิงวัตถุใน 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

class MyChild(MyParent):
   # Do stuff here
  • MyParent: คลาสที่นำฟังก์ชันการทำงานมาขยาย/สืบทอด
  • MyChild: คลาสที่จะสืบทอดฟังก์ชันการทำงานและเพิ่มเติมส่วนอื่น
การเขียนโปรแกรมเชิงวัตถุใน Python

คลาสลูกมีข้อมูลทั้งหมดของคลาสแม่

# Constructor inherited from BankAccount
savings_acct = SavingsAccount(1000)
type(savings_acct)
__main__.SavingsAccount
# Attribute inherited from BankAccount
savings_acct.balance
1000
# Method inherited from BankAccount
savings_acct.withdraw(300)
การเขียนโปรแกรมเชิงวัตถุใน Python

การสืบทอด: ความสัมพันธ์แบบ "is-a"

SavingsAccount คือ BankAccount

(อาจมีฟีเจอร์พิเศษเพิ่มเติม)

savings_acct = SavingsAccount(1000)
isinstance(savings_acct, SavingsAccount)
True
isinstance(savings_acct, BankAccount)
True

 

 

acct = BankAccount(500)
isinstance(acct,SavingsAccount)
False
isinstance(acct,BankAccount)
True
การเขียนโปรแกรมเชิงวัตถุใน Python

มาฝึกกันเถอะ!

การเขียนโปรแกรมเชิงวัตถุใน Python

Preparing Video For Download...