用python的运用构造方法,类和对象知识完成银行账号管理,要求具有用户界面,可以创建用户账户、查询用户账户、删除用户账户、存钱(存钱后账号金额增加)、取钱(取钱后账号金额减少)等功能
时间: 2023-08-16 17:08:08 浏览: 112
好的,我可以为您提供一个简单的代码示例,实现银行账号管理系统,具有用户界面,可以创建用户账户、查询用户账户、删除用户账户、存钱、取钱等功能。
```
class Account:
def __init__(self, name, balance=0):
self.name = name
self.balance = balance
def deposit(self, amount):
self.balance += amount
def withdraw(self, amount):
if amount > self.balance:
return "Insufficient balance"
else:
self.balance -= amount
def __str__(self):
return f"Account name: {self.name}\nBalance: {self.balance}"
class Bank:
def __init__(self):
self.accounts = {}
def create_account(self, name, balance=0):
if name in self.accounts:
return "Account already exists"
else:
self.accounts[name] = Account(name, balance)
return "Account created successfully"
def delete_account(self, name):
if name in self.accounts:
del self.accounts[name]
return "Account deleted successfully"
else:
return "Account does not exist"
def display_account(self, name):
if name in self.accounts:
return str(self.accounts[name])
else:
return "Account does not exist"
def deposit(self, name, amount):
if name in self.accounts:
self.accounts[name].deposit(amount)
return "Amount deposited successfully"
else:
return "Account does not exist"
def withdraw(self, name, amount):
if name in self.accounts:
return self.accounts[name].withdraw(amount)
else:
return "Account does not exist"
bank = Bank()
while True:
print("1. Create account")
print("2. Delete account")
print("3. Display account")
print("4. Deposit")
print("5. Withdraw")
print("6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
name = input("Enter account name: ")
balance = int(input("Enter initial balance (optional): "))
print(bank.create_account(name, balance))
elif choice == 2:
name = input("Enter account name: ")
print(bank.delete_account(name))
elif choice == 3:
name = input("Enter account name: ")
print(bank.display_account(name))
elif choice == 4:
name = input("Enter account name: ")
amount = int(input("Enter amount to deposit: "))
print(bank.deposit(name, amount))
elif choice == 5:
name = input("Enter account name: ")
amount = int(input("Enter amount to withdraw: "))
print(bank.withdraw(name, amount))
elif choice == 6:
break
else:
print("Invalid choice")
```
这个代码示例中,我们定义了两个类 `Account` 和 `Bank`。`Account` 类表示银行账户,具有账户名和余额两个属性,以及存款和取款两个方法;`Bank` 类表示银行,具有创建账户、删除账户、查询账户、存款和取款等功能。
在主程序中,我们使用一个 while 循环来显示用户界面,并根据用户输入的操作来调用相应的方法。用户可以通过输入数字来执行不同的操作,比如创建账户、删除账户、查询账户、存款和取款等。
阅读全文