编写一个银行账户类,包含账户余额、存款、取款等方法。python
时间: 2024-05-04 16:22:36 浏览: 197
以下是一个简单的银行账户类的代码示例:
```python
class BankAccount:
def __init__(self, balance=0):
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposit successful. New balance: {self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds")
else:
self.balance -= amount
print(f"Withdrawal successful. New balance: {self.balance}")
```
在这个类中,`__init__` 方法用于初始化账户余额,`deposit` 方法用于存款,`withdraw` 方法用于取款。这些方法都会更新账户余额并打印相关信息。
我们可以使用这个类来创建银行账户对象,并进行存取款操作:
```python
# 创建账户对象,初始余额为 0
account = BankAccount()
# 存款 100 元
account.deposit(100)
# 取款 50 元
account.withdraw(50)
# 尝试取款 1000 元,失败
account.withdraw(1000)
```
输出结果:
```
Deposit successful. New balance: 100
Withdrawal successful. New balance: 50
Insufficient funds
```
阅读全文