讀古今文學網 > 父與子的編程之旅:與小卡特一起學Python > 第14章 >

第14章

測試題

1. 要定義一個新的對象類型,需要使用 class 關鍵字。

2. 屬性是有關一個對像「你所知道的信息」,就是包含在對像中的變量。

3. 方法是可以對對像做的「動作」,就是包含在對像中的函數。

4. 類只是對象的定義或藍圖,從這個藍圖建立對像時得到的就是實例。

5. 在對像方法中通常用 self 作為實例引用。

6. 多態是指不同對象可以有同名的兩個或多個方法。這些方法可以根據它們所屬的對象有不同的行為。

7. 繼承是指對像能夠從它們的「雙親」(父類)得到屬性和方法。「子」類(也稱為子類或派生類)會得到父類的所有屬性和方法,還可以有父類所沒有的屬性和方法。

動手試一試

1. 對應銀行賬戶的類如下所示:

class BankAccount:    def __init__(self, acct_number, acct_name):self.acct_number = acct_numberself.acct_name = acct_nameself.balance = 0.0    def displayBalance(self):print "The account balance is:", self.balance    def deposit(self, amount):self.balance = self.balance + amountprint "You deposited", amountprint "The new balance is:", self.balance    def withdraw(self, amount):if self.balance >= amount:    self.balance = self.balance - amount    print "You withdrew", amount    print "The new balance is:", self.balanceelse:    print "You tried to withdraw", amount    print "The account balance is:", self.balance    print "Withdrawal denied. Not enough funds."  

下面的代碼用來測試這個類,確保它能正常工作:

myAccount = BankAccount(234567, "Warren Sande")print "Account name:", myAccount.acct_nameprint "Account number:", myAccount.acct_numbermyAccount.displayBalancemyAccount.deposit(34.52)myAccount.withdraw(12.25)myAccount.withdraw(30.18)  

2. 要建立一個利息賬戶,需要建立一個 BankAccount 子類,並創建一個方法來增加利息:

class InterestAccount(BankAccount):    def __init__(self, acct_number, acct_name, rate):BankAccount.__init__(self, acct_number, acct_name)self.rate = rate    def addInterest (self):interest = self.balance * self.rateprint"adding interest to the account,",self.rate * 100," percent"self.deposit (interest)  

下面是一些測試代碼:

myAccount = InterestAccount(234567, "Warren Sande", 0.11)print "Account name:", myAccount.acct_nameprint "Account number:", myAccount.acct_numbermyAccount.displayBalancemyAccount.deposit(34.52)myAccount.addInterest