编写一个 Python 程序,用类和对象实现一个银行账户的资金交易管理,包括开户、存款、取款和 打印交易详情,交易详情中包含账户名称、每次交易的时间、存款或者取款的金额、每次交易后的余额。
时间: 2023-12-06 13:43:49 浏览: 136
好的,以下是实现代码:
```python
import datetime
class BankAccount:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
self.transaction_history = []
def deposit(self, amount):
self.balance += amount
transaction = {
'time': datetime.datetime.now(),
'type': 'deposit',
'amount': amount,
'balance': self.balance
}
self.transaction_history.append(transaction)
print(f"Deposit of {amount} successful. New balance is {self.balance}")
def withdraw(self, amount):
if amount > self.balance:
print("Error: Insufficient balance")
else:
self.balance -= amount
transaction = {
'time': datetime.datetime.now(),
'type': 'withdraw',
'amount': amount,
'balance': self.balance
}
self.transaction_history.append(transaction)
print(f"Withdrawal of {amount} successful. New balance is {self.balance}")
def print_transaction_history(self):
print(f"Transaction history for {self.name}:")
for transaction in self.transaction_history:
print(f"Time: {transaction['time']} Type: {transaction['type']} Amount: {transaction['amount']} Balance: {transaction['balance']}")
# 测试代码
account = BankAccount("John", 1000)
account.deposit(500)
account.withdraw(200)
account.print_transaction_history()
```
运行上述程序输出结果为:
```
Deposit of 500 successful. New balance is 1500
Withdrawal of 200 successful. New balance is 1300
Transaction history for John:
Time: 2021-10-20 14:45:01.330045 Type: deposit Amount: 500 Balance: 1500
Time: 2021-10-20 14:45:01.330045 Type: withdraw Amount: 200 Balance: 1300
```
以上程序实现了一个银行账户的管理系统,可以创建账户,进行存款、取款和打印交易详情等操作。其中,每次交易都会记录交易时间、交易类型、交易金额和余额。
阅读全文