1、定义银行帐户类,变量有“帐号”和“存款余额”,“存取历史〞,方法有“存 款”、“取款”、“查询余额”、〞品示帐号”以及存储功能,能查询历史存取记录
时间: 2023-06-14 22:04:52 浏览: 177
python中的实例方法、静态方法、类方法、类变量和实例变量浅析
以下是银行账户类的定义,其中包含了帐号、存款余额、存取历史等属性,以及对应的方法实现:
```python
class BankAccount:
def __init__(self, account_num):
self.account_num = account_num
self.balance = 0
self.history = []
def deposit(self, amount):
self.balance += amount
self.history.append('Deposit: +{}'.format(amount))
def withdraw(self, amount):
if amount > self.balance:
print('Insufficient funds')
else:
self.balance -= amount
self.history.append('Withdrawal: -{}'.format(amount))
def get_balance(self):
return self.balance
def display_account_num(self):
print('Account number:', self.account_num)
def show_history(self):
print('Transaction history:')
for transaction in self.history:
print(transaction)
```
以上就是一个简单的银行账户类的实现,可以通过实例化这个类来创建一个具体的银行账户对象。例如,我们可以这样创建一个账户并进行存款、取款、查询余额、查询历史交易记录等操作:
```python
# Create a bank account
my_account = BankAccount('0001')
# Deposit some money
my_account.deposit(1000)
# Withdraw some money
my_account.withdraw(500)
# Check the balance
print('Current balance:', my_account.get_balance())
# Display the account number
my_account.display_account_num()
# Show the transaction history
my_account.show_history()
```
输出结果如下:
```
Current balance: 500
Account number: 0001
Transaction history:
Deposit: +1000
Withdrawal: -500
```
阅读全文