如何实例化银行帐户类中的几个帐户

  • 本文关键字:几个 实例化 python
  • 更新时间 :
  • 英文 :


我必须编写代码来实例化一个类中的几个对象(银行账户(。我编写了使用单个对象检查余额、取款和存款的功能。然而,我不知道如何使它为每个对象重复类。我也不知道如何让检查余额、存款或从对象中提取的选择适用于正确的对象。除此之外,我不知道如何为每个对象运行检查余额、存款和取款的功能。

代码:

class Account:
def __init__(self, name, account_number, balance):
print("Welcome to the bank.")
self.name=name
self.account_number=account_number
self.balance=balance


def check_balance(self):
print ("Balance:", self.balance)
def deposit(self):
print("Current balance:", self.balance)
str2=input("How much would you like to deposit? ")
str2=int(str2)
print ("Current Balance:", self.balance + str2)
def withdraw(self):
print ("Current Balance", self.balance)
str4=input("How much would you like to withdraw? ")
str4=int(str4)
if self.balance - str4 < 0:
print("Unable to process. Doing this will result in a negative balance.")
elif self.balance - str4 >= 0:
print("Current Balance:", self.balance - str4)

str3=input("Would you like to check the balance of the account, deposit money into the account, or withdraw money from the account? ")
if str3=="check the balance":
self.check_balance()
elif str3=="deposit money":
self.deposit()
elif str3=="withdraw money":
self.withdraw()
else:
print("Unable to process.")
Fred=Account("Fred",20,30)
John=Account("John",30,40)
Michelle=Account("Michelle",40,50)
Ann=Account("Ann",50,60)

这里有一些设计问题。

  1. 不要将帐户存储在4个单独的变量中。将它们存储在列表中,这样您就可以按账号(如果您想添加账号,也可以按姓名(查找它们。这样可以更容易地将帐户保存到文件中并读回,这是您需要做的

  2. Account只是一个存储信息的地方。不要让它做任何I/O。不要让它与用户交互。

  3. 您需要询问用户使用哪个帐户。

  4. 你应该循环直到它们完成。

在这里,我每次都要一个帐号。为了让这更智能,你可以要求一个帐户,并继续允许该帐户上的选项,使用另一个菜单项切换到另一个帐户。

你可以把帐号作为关键字存储在字典里。这将比简单的清单更明智。

class Account:
def __init__(self, name, account_number, balance):
self.name=name
self.account_number=account_number
self.balance=balance
def deposit(self, amt):
self.balance += amt
return self.balance
def withdraw(self,amt):
if self.balance < amt:
return self.balance - amt
self.balance -= amt
return self.balance

accounts = [
Account("Fred",20,30),
Account("John",30,40),
Account("Michelle",40,50),
Account("Ann",50,60)
]
print("Welcome to the bank.")
while True:
acct = int(input("Which account number are you working with today? "))
acct = [a for a in accounts if a.account_number == acct]
if not acct:
print("That account doesn't exist.")
continue
acct = acct[0]
print("nBalance: ", acct.balance)
print("Would you like to:")
print(" 1. Check the balance")
print(" 2. Deposit money")
print(" 3. Withdraw money")
print(" 4. Quit")
str3 = input("Pick in option: ")
if str3=="1":
print("Balance: ", acct.balance)
elif str3=="2":
amt=int(input("How much would you like to deposit? "))
acct.deposit( amt )
elif str3=="3":
amt=int(input("How much would you like to withdraw? "))
if acct.withdraw( amt ) < 0:
print("Unable to process. Doing this will result in a negative balance.")
elif str3=="4":
break
else:
print("Unrecognized.")

最新更新