第 14 章
测试题
要定义一个新的对象类型,需要使用
class关键字。属性是有关一个对象“你所知道的信息”,就是包含在对象中的变量。
方法是可以对对象做的“动作”,就是包含在对象中的函数。
类只是对象的定义或蓝图,从这个蓝图建立对象时得到的就是实例。
在对象方法中通常用
self作为实例引用。多态是指不同对象可以有同名的两个或多个方法。这些方法可以根据它们所属的对象有不同的行为。
继承是指对象能够从它们的“双亲”(父类)得到属性和方法。“子”类(也称为子类或派生类)会得到父类的所有属性和方法,还可以有父类所没有的属性和方法。
动手试一试
- 对应银行账户的类如下所示:
class BankAccount:def __init__(self, acct_number, acct_name):self.acct_number = acct_numberself.acct_name = acct_nameself.balance = 0.0def displayBalance(self):print "The account balance is:", self.balancedef deposit(self, amount):self.balance = self.balance + amountprint "You deposited", amountprint "The new balance is:", self.balancedef withdraw(self, amount):if self.balance >= amount:self.balance = self.balance - amountprint "You withdrew", amountprint "The new balance is:", self.balanceelse:print "You tried to withdraw", amountprint "The account balance is:", self.balanceprint "Withdrawal denied. Not enough funds."
下面的代码用来测试这个类,确保它能正常工作:
myAccount = BankAccount(234567, "Warren Sande")print "Account name:", myAccount.acct_nameprint "Account number:", myAccount.acct_numbermyAccount.displayBalance()myAccount.deposit(34.52)myAccount.withdraw(12.25)myAccount.withdraw(30.18)
- 要建立一个利息账户,需要建立一个
BankAccount子类,并创建一个方法来增加利息:
class InterestAccount(BankAccount):def __init__(self, acct_number, acct_name, rate):BankAccount.__init__(self, acct_number, acct_name)self.rate = ratedef 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.displayBalance()myAccount.deposit(34.52)myAccount.addInterest()
