1. 为BankAccount 建立一个类定义。它应该有一些属性,包括账户名(一个字
符串)、账号(一个字符串或整数)和余额(一个浮点数),另外还要有一些
方法显示余额、存钱和取钱。
class BankAccount: def __init__(self,account,account_id,account_balance): self.account = account self.account_id = account_id self.account_balance =account_balance def getBalance(self):#显示余额 balance = self.account_balance return balance print("余额为",balance) def saveMoney(self,money):#显示存钱 self.account_balance = self.account_balance + money print("存入",money) print("现在账户余额",self.account_balance) def withDraw(self,getmoney): surplus = self.account_balance - getmoney if getmoney>self.account_balance: print("余额不足") else: print("你已取出:",getmoney,"元") print("您的",self.account_id,"账户剩余:",surplus)
self.account_balance =surplus #如果未对self.account_balance赋上修改取出后的值,则可能导致上次扣除后余额不更新
#可以取消赋值
#else:
# self.account_balance = self.account_balance -getmoey
# print("你已取出",getmoney,"元")
# print("您的",self.account_id,"账户剩余",self.account_balance)
"""看过一些文章说的是把初始的账户余额定为0的,而我这个设置为参数,输入余额"""
a = BankAccount("叶","yescarf",18) a.saveMoney(100) a.withDraw(150) a.withDraw(12)
2. 建立一个可以挣利息的类,名为InterestAccount。这应当是BankAccount
的一个子类(所以会继承BankAccount 的属性和方法)。InterestAccount
还应当有一个对应利息率的属性,另外有一个方法来增加利息。为了力求简
单,假设每年会调用一次addInterest() 方法计算利息并更新余额。
class BankAccount: def __init__(self,account,account_id,account_balance): self.account = account self.account_id = account_id self.account_balance =account_balance def getBalance(self):#显示余额 balance = self.account_balance return balance print("余额为",balance) def saveMoney(self,money):#显示存钱 self.account_balance = self.account_balance + money print("存入",money) print("现在账户余额",self.account_balance) def withDraw(self,getmoney): surplus = self.account_balance - getmoney if getmoney>self.account_balance: print("余额不足") else: print("你已取出:",getmoney,"元") print("您的",self.account_id,"账户剩余:",surplus) self.account_balance =surplus #如果未对self.account_balance赋上修改取出后的值,则可能导致依旧按元先账户余额计算结果,导致错误 """a = BankAccount("叶","yescarf",18) a.saveMoney(100) a.withDraw(150) a.withDraw(12)""" class InterestAccount(BankAccount): def __init__(self,rate): BankAccount.__init__(self,"weimiaomiao", 123456,0)#init继承 self.rate = rate def addInterest(self): interest =self.account_balance *self.rate surplus = interest+self.account_balance print("利息为",interest) print("结余余额为",surplus) b= InterestAccount(0.2) b.saveMoney(100) b.saveMoney() b.withDraw(20.5) b.withDraw(50) b.addInterest()