(2)设计银行卡类并进行测试,该类有账户名、卡号、余额、状态(是否正常)等属性,并实现存、取、转账等操作。Python类与对象
时间: 2024-12-14 17:21:52 浏览: 19
在Python中,我们可以设计一个简单的银行卡类(BankAccount),包含基本的属性如账户名(account_name)、卡号(card_number)、余额(balance)和状态(status)。为了表示卡片是否正常,我们通常将状态设置为True表示正常,False表示异常。接下来我会展示如何创建这个类,并提供一些基本方法,如存款(deposit), 取款(withdraw), 转账(transfer)。
```python
class BankAccount:
def __init__(self, account_name, card_number, initial_balance=0, is_active=True):
self.account_name = account_name
self.card_number = card_number
self.balance = initial_balance
self.is_active = is_active
# 存款方法
def deposit(self, amount):
if amount > 0:
self.balance += amount
return f"已成功存入{amount}元,当前余额为{self.balance}"
else:
return "无效金额,无法存款"
# 取款方法
def withdraw(self, amount):
if amount <= self.balance and amount > 0:
self.balance -= amount
return f"已成功取出{amount}元,当前余额为{self.balance}"
elif amount == 0:
return "无需提取零钱"
else:
return "余额不足,无法取款"
# 转账方法
def transfer(self, to_account, amount):
if amount > 0 and self.balance >= amount and to_account.is_active:
self.balance -= amount
to_account.balance += amount
return f"已成功向{to_account.account_name}转账{amount}元,当前余额为{self.balance}"
else:
return "转账失败,请检查金额和余额"
# 测试示例
account1 = BankAccount("张三", "1234567890")
account2 = BankAccount("李四", "0987654321", 500)
print(account1.deposit(200))
print(account1.withdraw(150))
print(account1.transfer(account2, 100))
```
阅读全文