การปรับแต่งฟังก์ชันการทำงานผ่าน Inheritance

Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

George Boorman

Curriculum Manager, DataCamp

ลำดับชั้นของคลาส bank 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
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การปรับแต่ง Constructor

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
  • เรียก constructor ของ parent class ก่อนได้ด้วย Parent.__init__(self, args...)
  • เพิ่มฟังก์ชันการทำงานได้อีก
  • ไม่จำเป็นต้องเรียก constructor ของ parent class เสมอไป
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

สร้างออบเจ็กต์ด้วย Constructor ที่ปรับแต่งแล้ว

# Construct the object using the new constructor
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การเพิ่มฟังก์ชันการทำงาน

  • เพิ่ม method ได้ตามปกติ
  • ใช้ข้อมูลจากทั้ง parent class และ child class ได้
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 เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

ลำดับชั้นของคลาส bank account

Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

การเพิ่ม Child Class ที่สอง

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 เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ
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'
  • ละเมิด polymorphism
    • parent class และ child class มี method ที่ต่างกัน
Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

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

Python เบื้องต้นสำหรับการเขียนโปรแกรมเชิงวัตถุ

Preparing Video For Download...