用python银行账户BankAccount类
时间: 2023-12-17 18:03:37 浏览: 275
好的,我可以为您编写一个简单的银行账户BankAccount类的Python实现。以下是代码示例:
```python
class BankAccount:
def __init__(self, account_number, account_holder, balance=0):
self.account_number = account_number
self.account_holder = account_holder
self.balance = balance
def deposit(self, amount):
self.balance += amount
print(f"Deposit of {amount} successful. Current balance: {self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Insufficient funds.")
else:
self.balance -= amount
print(f"Withdrawal of {amount} successful. Current balance: {self.balance}")
```
该类有三个属性:账户号、账户持有人和余额。其中,账户号和账户持有人在初始化时必须提供,而余额可以在初始化时提供默认值0。该类还有两个方法:存款和取款。存款方法将提供的金额加到余额中,并显示存款成功的消息;取款方法将检查余额是否足够支付提供的金额,如果足够,则从余额中减去提供的金额并显示取款成功的消息,否则显示资金不足的消息。
您可以使用以下代码示例来创建和操作BankAccount对象:
```python
# 创建一个账户对象
my_account = BankAccount("1234567890", "John Smith", 1000)
# 存款
my_account.deposit(500)
# 取款
my_account.withdraw(200)
# 取款(资金不足)
my_account.withdraw(2000)
```
这将显示以下输出:
```
Deposit of 500 successful. Current balance: 1500
Withdrawal of 200 successful. Current balance: 1300
Insufficient funds.
```
阅读全文