如何用python的类写一个存取款系统
时间: 2023-06-05 20:04:23 浏览: 57
可以使用一个Account类来实现存取款系统,类中包含账户名、账号、余额等属性,以及存款、取款、查询余额等方法。以下是一个简单的示例代码:
```python
class Account:
def __init__(self, name, number, balance=0):
self.name = name
self.number = number
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"成功存入{amount}元,当前余额为{self.balance}元")
def withdraw(self, amount):
if amount > self.balance:
print("余额不足,取款失败")
else:
self.balance -= amount
print(f"成功取出{amount}元,当前余额为{self.balance}元")
def check_balance(self):
print(f"当前余额为{self.balance}元")
```
使用时可以先创建一个Account对象,然后调用其方法进行操作:
```python
# 创建账户
my_account = Account("张三", "123456", 100)
# 存款
my_account.deposit(50) # "成功存入50元,当前余额为150元"
# 取款
my_account.withdraw(80) # "成功取出80元,当前余额为70元"
my_account.withdraw(100) # "余额不足,取款失败"
# 查询余额
my_account.check_balance() # "当前余额为70元"
```