存折与信用卡(继承)Python

目录

题目描述

思路分析

AC代码


题目描述

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

从存折类派生出信用卡类CCreditcard,信用卡类增加了透支限额(limit,float)一项数据成员,对取款操作进行修改,允许在限额范围内透支金额,超出范围取款提示“sorry! over limit!”。注意,在本题中,balance可以是负数,例如当余额为500,可透支金额为500,取款800时,则balance为 - 300。

编写主函数,建立这两个类的对象并测试之。

1.对于存折类,输入账号、姓名、余额后,按照查询余额、存款、查询余额、取款、查询余额的顺序调用类方法并输出。

2.对于信用卡类,输入账号、姓名、余额、透支限额后,按照查询余额、存款、查询余额、取款、查询余额的顺序调用类方法并输出。

输入

账号 姓名 余额

存款金额

取款金额

账号 姓名 余额 透支限额

存款金额

取款金额

输出

账户余额

存款操作结果

账户余额

取款操作结果

账户余额

账户余额

存款操作结果

账户余额

取款操作结果

账户余额

输入样例1 

1000 Tom 1000
500
1000
2000 John 500 500
500
1501

输出样例1

balance is 1000
saving ok!
balance is 1500
withdraw ok!
balance is 500
balance is 500
saving ok!
balance is 1000
sorry! over limit!
balance is 1000

思路分析

一开始我把属性都设定为私有属性,然后在类外用子类对象调用父类方法的时候,报错了:
AttributeError: 'CAccount' object has no attribute '_CAccount__balance'.

然后折腾了好久,问了很多前辈,最后还是得靠自己,我最后意识到和权限有关系,python只有公有属性和私有属性,继承下来后,子类可以拥有私有属性,但是不能访问,所以我只能把冲突的属性改为公有解决问题。

AC代码

class CAccount:
    def datain(self):
        self.__account, self.__name, self.balance=input().split()
        self.__account=int(self.__account)
        self.balance=float(self.balance)
    def deposit(self):
        amount=float(input())
        self.balance= self.balance + amount
        print('saving ok!')
    def withdraw(self):
        amount=float(input())
        if amount>self.balance:
            print('sorry! over balance!')
            return
        self.balance= self.balance - amount
        print('withdraw ok!')
    def check(self):
        print('balance is %.0f' % (self.balance))
class CCreditcard(CAccount):
    def datain(self):
        self.__account, self.__name, self.balance, self.__limit=input().split()
        self.__account=int(self.__account)
        self.balance=float(self.balance)
        self.__limit=float(self.__limit)
    def withdraw(self):
        amount=float(input())
        if amount>self.balance+self.__limit:
            print('sorry! over limit!')
            return
        self.balance= self.balance - amount
        print('withdraw ok!')
account=CAccount()
account.datain()
account.check()
account.deposit()
account.check()
account.withdraw()
account.check()
creditcard=CCreditcard()
creditcard.datain()
creditcard.check()
creditcard.deposit()
creditcard.check()
creditcard.withdraw()
creditcard.check()

猜你喜欢

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