存折类定义(类与对象)Python

 目录

题目描述

思路分析

AC代码


题目描述

定义一个存折类CAccount,存折类具有帐号(account, long)、姓名(name,char[10])、余额(balance,float)等数据成员,可以实现存款(deposit,操作成功提示“saving ok!”)、取款(withdraw,操作成功提示“withdraw ok!”)和查询余额(check)的操作,取款金额必须在余额范围内,否则提示“sorry! over limit!”。

编写主函数,建立这个类的对象并测试,输入账号、姓名、余额后,按照查询余额、存款、查询余额、取款、查询余额的顺序调用类方法并输出。

输入

第一个存折的账号、姓名、余额

存款金额

取款金额

第二个存折的账号、姓名、余额

存款金额

取款金额

输出

第一个存折的账户余额

存款操作结果

账户余额

取款操作结果

账户余额

第二个存折的账户余额

存款操作结果

账户余额

取款操作结果

账户余额

输入样例1 

9111 Tom 1000
500
1000
92220 John 500
500
1500

输出样例1

Tom's balance is 1000
saving ok!
Tom's balance is 1500
withdraw ok!
Tom's balance is 500
John's balance is 500
saving ok!
John's balance is 1000
sorry! over limit!
John's balance is 1000

思路分析

呃 有空再写了,先偷个懒。

好吧还是写吧。

一开始写成这样:

class CAccount:
    def datain(self):
        self.account,self.name,self.balance=input(),input(),float(input())

发现这样的话,accout和name会读取整一个带空格的字符串。

于是只能先全读了,再强制转换:

class CAccount:
    def datain(self):
        self.account,self.name,self.balance=input().split()
        self.balance=float(self.balance)

AC代码

class CAccount:
    def datain(self):
        self.account,self.name,self.balance=input().split()
        self.balance=float(self.balance)
    def deposit(self):
        self.plus=int(input())
        self.balance=self.balance+self.plus
        print("saving ok!")
    def withdraw(self):
        self.minus=int(input())
        if self.minus>self.balance:
            print("sorry! over limit!")
            return
        self.balance=self.balance-self.minus
        print("withdraw ok!")
    def check(self):
        print("%s's balance is %.0f"%(self.name,self.balance))
a,b=CAccount(),CAccount()
a.datain()
a.check()
a.deposit()
a.check()
a.withdraw()
a.check()
b.datain()
b.check()
b.deposit()
b.check()
b.withdraw()
b.check()

猜你喜欢

转载自blog.csdn.net/weixin_62264287/article/details/125769996