Tùy chỉnh chức năng thông qua kế thừa

Nhập môn Lập trình Hướng đối tượng với Python

George Boorman

Curriculum Manager, DataCamp

Một hệ thống phân cấp các lớp tài khoản ngân hàng

Nhập môn Lập trình Hướng đối tượng với Python

Những gì chúng ta đã có đến nay

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
Nhập môn Lập trình Hướng đối tượng với Python

Tùy chỉnh hàm tạo

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
  • Có thể chạy constructor của lớp cha trước bằng Parent.__init__(self, args...)
  • Thêm nhiều chức năng hơn
  • Không cần gọi hàm tạo của lớp cha
Nhập môn Lập trình Hướng đối tượng với Python

Tạo đối tượng với hàm tạo tùy chỉnh

# Construct the object using the new constructor
acct = SavingsAccount(1000, 0.03)
acct.interest_rate
0.03
Nhập môn Lập trình Hướng đối tượng với Python

Thêm chức năng

  • Thêm phương thức như thường lệ
  • Có thể sử dụng dữ liệu từ cả lớp cha và lớp con
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)
Nhập môn Lập trình Hướng đối tượng với Python

Một hệ thống phân cấp các lớp tài khoản ngân hàng

Nhập môn Lập trình Hướng đối tượng với Python

Thêm lớp con thứ hai

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
Nhập môn Lập trình Hướng đối tượng với 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'
  • Vi phạm đa hình
    • Các lớp cha / con có các phương thức khác nhau
Nhập môn Lập trình Hướng đối tượng với Python

Hãy luyện tập!

Nhập môn Lập trình Hướng đối tượng với Python

Preparing Video For Download...