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