python银行账户bankaccount类
时间: 2023-10-09 17:09:58 浏览: 307
下面是一个简单的Python银行账户BankAccount类示例:
```python
class BankAccount:
def __init__(self, account_number, owner_name, balance):
self.account_number = account_number
self.owner_name = owner_name
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if self.balance < amount:
print("Insufficient funds")
else:
self.balance -= amount
def get_balance(self):
return self.balance
def __str__(self):
return f"Account Number: {self.account_number}, Owner Name: {self.owner_name}, Balance: {self.balance}"
```
这个类有三个属性:账户号码(account_number),所有人姓名(owner_name)和余额(balance)。它还有四个方法:存款(deposit),取款(withdraw),查询余额(get_balance)和字符串表示形式(__str__)。
在初始化方法中,我们传入账户号码、所有人姓名和初始余额。在存款方法中,我们将传入的金额加到余额上。在取款方法中,如果余额不足,则打印“余额不足”的消息。否则,我们从余额中减去取款金额。在查询余额方法中,我们简单地返回余额。在__str__方法中,我们返回一个字符串,其中包含账户号码、所有人姓名和余额的信息。
下面是一个示例用法:
```python
# 创建一个账户
my_account = BankAccount("1234567890", "John Doe", 1000.0)
# 存款$500
my_account.deposit(500.0)
# 取款$200
my_account.withdraw(200.0)
# 查询余额
print("Current balance:", my_account.get_balance())
# 打印账户信息
print(my_account)
```
输出:
```
Current balance: 1300.0
Account Number: 1234567890, Owner Name: John Doe, Balance: 1300.0
```
阅读全文