第 14 章

测试题

  1. 要定义一个新的对象类型,需要使用 class 关键字。

  2. 属性是有关一个对象“你所知道的信息”,就是包含在对象中的变量。

  3. 方法是可以对对象做的“动作”,就是包含在对象中的函数。

  4. 类只是对象的定义或蓝图,从这个蓝图建立对象时得到的就是实例。

  5. 在对象方法中通常用 self 作为实例引用。

  6. 多态是指不同对象可以有同名的两个或多个方法。这些方法可以根据它们所属的对象有不同的行为。

  7. 继承是指对象能够从它们的“双亲”(父类)得到属性和方法。“子”类(也称为子类或派生类)会得到父类的所有属性和方法,还可以有父类所没有的属性和方法。

动手试一试

  1. 对应银行账户的类如下所示:
  1. class BankAccount:
  2. def __init__(self, acct_number, acct_name):
  3. self.acct_number = acct_number
  4. self.acct_name = acct_name
  5. self.balance = 0.0
  6. def displayBalance(self):
  7. print "The account balance is:", self.balance
  8. def deposit(self, amount):
  9. self.balance = self.balance + amount
  10. print "You deposited", amount
  11. print "The new balance is:", self.balance
  12. def withdraw(self, amount):
  13. if self.balance >= amount:
  14. self.balance = self.balance - amount
  15. print "You withdrew", amount
  16. print "The new balance is:", self.balance
  17. else:
  18. print "You tried to withdraw", amount
  19. print "The account balance is:", self.balance
  20. print "Withdrawal denied. Not enough funds."

下面的代码用来测试这个类,确保它能正常工作:

  1. myAccount = BankAccount(234567, "Warren Sande")
  2. print "Account name:", myAccount.acct_name
  3. print "Account number:", myAccount.acct_number
  4. myAccount.displayBalance()
  5. myAccount.deposit(34.52)
  6. myAccount.withdraw(12.25)
  7. myAccount.withdraw(30.18)
  1. 要建立一个利息账户,需要建立一个 BankAccount 子类,并创建一个方法来增加利息:
  1. class InterestAccount(BankAccount):
  2. def __init__(self, acct_number, acct_name, rate):
  3. BankAccount.__init__(self, acct_number, acct_name)
  4. self.rate = rate
  5. def addInterest (self):
  6. interest = self.balance * self.rate
  7. print"adding interest to the account,",self.rate * 100," percent"
  8. self.deposit (interest)

下面是一些测试代码:

  1. myAccount = InterestAccount(234567, "Warren Sande", 0.11)
  2. print "Account name:", myAccount.acct_name
  3. print "Account number:", myAccount.acct_number
  4. myAccount.displayBalance()
  5. myAccount.deposit(34.52)
  6. myAccount.addInterest()