设计一个管理银行账户的类,要求有两个类属性: 开户数量以及总存款额;两个 实例属性:户名与个人存款额:两个普通的实例方法: 取钱与存钱:四个类方法: 总存款额增 减以及开户量增减,还要实现特殊方法_str_。最后,生成两个实例并作简单的测试!
时间: 2024-02-05 16:04:41 浏览: 125
bank.rar_存款系统银行_银行管理系统_银行管理销户
好的,以下是我的代码实现:
```python
class BankAccount:
num_of_accounts = 0
total_deposits = 0
def __init__(self, name, balance):
self.name = name
self.balance = balance
BankAccount.num_of_accounts += 1
BankAccount.total_deposits += balance
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient funds"
else:
self.balance -= amount
BankAccount.total_deposits -= amount
return "Withdrawal successful"
def deposit(self, amount):
self.balance += amount
BankAccount.total_deposits += amount
return "Deposit successful"
@classmethod
def increase_num_of_accounts(cls):
cls.num_of_accounts += 1
@classmethod
def decrease_num_of_accounts(cls):
cls.num_of_accounts -= 1
@classmethod
def increase_total_deposits(cls, amount):
cls.total_deposits += amount
@classmethod
def decrease_total_deposits(cls, amount):
cls.total_deposits -= amount
def __str__(self):
return f"Account holder: {self.name}\nAccount balance: {self.balance}"
# 测试代码
account1 = BankAccount("John Smith", 5000)
account2 = BankAccount("Jane Doe", 10000)
print(f"Number of accounts: {BankAccount.num_of_accounts}")
print(f"Total deposits: {BankAccount.total_deposits}")
account1.withdraw(2000)
print(account1)
account1.deposit(500)
print(account1)
BankAccount.increase_num_of_accounts()
BankAccount.increase_total_deposits(3000)
print(f"Number of accounts: {BankAccount.num_of_accounts}")
print(f"Total deposits: {BankAccount.total_deposits}")
```
输出结果为:
```
Number of accounts: 2
Total deposits: 15000
Account holder: John Smith
Account balance: 3000
Account holder: John Smith
Account balance: 3500
Number of accounts: 3
Total deposits: 18000
```
阅读全文