【问题描述】模拟用钱包购买商品的行为。要求实现一个钱包报警异常类,钱包类,信用卡类以及主类,当钱包现金不够支付的时候用信用卡支付,如果信用卡也不够支付则不够买该商品 【输入形式】 主类首先输入钱包中现金数量,精确到小数点后两位 第二行输入信用卡的信用额度 第三行输入信用卡已透支的额度 第四行开始输入支付额度直到输入字符串或钱包不能支付为止为止 【输出形式】输出支付信息 【样例输入】 2000 5000 1000 500 2300 4000 【样例输出】 Cash payments:500.00,Remaining cash:1500.00,Credit card availability:4000.00 Cash payments:1500.00,Remaining cash:0.00,Credit card availability:4000.00 Credit card payments:800.00,Remaining cash:0.00,Credit card availability:3200.00 Wallet Exception,Insufficient credit card balance to pay!
时间: 2024-02-11 08:06:41 浏览: 18
好的,根据您的问题描述,我可以提供以下代码实现:
```python
class WalletException(Exception):
def __init__(self, message):
super().__init__(message)
Wallet:
def __init__(self, cash):
self.cash = cash
def pay_cash(self, amount):
if self.cash < amount:
raise WalletException("Insufficient cash balance to pay!")
self.cash -= amount
print(f"Cash payments:{amount:.2f},Remaining cash:{self.cash:.2f}", end=",")
def pay_credit_card(self, amount, credit_card):
if credit_card.available_balance() < amount:
raise WalletException("Insufficient credit card balance to pay!")
credit_card.pay(amount)
print(f"Credit card payments:{amount:.2f},Remaining cash:{self.cash:.2f},Credit card availability:{credit_card.available_balance():.2f}", end=",")
class CreditCard:
def __init__(self, credit_limit, credit_used):
self.credit_limit = credit_limit
self.credit_used = credit_used
def available_balance(self):
return self.credit_limit - self.credit_used
def pay(self, amount):
if self.available_balance() < amount:
raise WalletException("Insufficient credit card balance to pay!")
self.credit_used += amount
if __name__ == "__main__":
cash = float(input())
credit_limit = float(input())
credit_used = float(input())
wallet = Wallet(cash)
credit_card = CreditCard(credit_limit, credit_used)
while True:
try:
amount = float(input())
wallet.pay_cash(amount)
except ValueError:
break
except WalletException as e:
try:
wallet.pay_credit_card(amount, credit_card)
except WalletException as e:
print(e)
break
else:
print("Wallet Exception,No more payments to make!")
```
主要思路是使用三个类,分别是`Wallet`(钱包类)、`CreditCard`(信用卡类)和`WalletException`(钱包报警异常类)。其中,钱包类和信用卡类分别定义了现金支付和信用卡支付的方法,并在支付时进行余额判断,如余额不足则抛出钱包异常类。主程序中,先输入钱包中现金数量、信用卡的信用额度和信用卡已透支的额度,然后循环输入支付额度,直到输入字符串或钱包不能支付为止。在循环中,先尝试使用钱包支付,如余额不足则使用信用卡支付,如信用卡余额也不足则抛出钱包异常类。最后,如果循环正常结束,则输出“Wallet Exception,No more payments to make!”。