我是一名初级程序员,正在构建一个程序,模拟一个拥有多个银行账户的银行,用户可以提取现金,创建账户,获取汇率等等。目前,我正在尝试访问一个组我班级中的所有实例,都是我的帐户类的对象。 Account Manager类负责管理这些帐户对象,并在需要用户输入时帮助组织它们。现在,我正在尝试在我的菜单上模拟我的第三个选项,该选项获取用户选择帐户的信息(他们必须手动输入他们帐户的ID以便检索信息,提取/存入现金等) )。虽然我已经设法将所有这些类实例存储在一个列表中,但我似乎无法使用我的get_account方法来检索它们以供使用。我将在下面发布我的所有代码。如果您发现其他任何不合适的地方,请随时告诉我。 代码:
# Virtual Bank
# 3/21/13
# Account Manager Class
class AccountManager(object):
"""Manages and handles accounts for user access"""
# Initial
def __init__(self):
self.accounts = []
# create account
def create_account(self, ID, bal = 0):
# Check for uniqueness? Possible method/exception??? <- Fix this
account = Account(ID, bal)
self.accounts.append(account)
def get_account(self, ID):
for account in self.accounts:
if account.ID == ID:
return account
else:
return "That is not a valid account. Sending you back to Menu()"
Menu()
class Account(object):
"""An interactive bank account."""
wallet = 0
# Initial
def __init__(self, ID, bal):
print("A new account has been created!")
self.id = ID
self.bal = bal
def __str__(self):
return "|Account Info| \nAccount ID: " + self.id + "\nAccount balance: $" + self.bal
# Main
AccManager = AccountManager()
def Menu():
print(
"""
0 - Leave the Virtual Bank
1 - Open a new account
2 - Get info on an account
3 - Withdraw money
4 - Deposit money
5 - Transfer money from one account to another
6 - Get exchange rates(Euro, Franc, Pounds, Yuan, Yen)
"""
) # Add more if necessary
choice = input("What would you like to do?: ")
while choice != "0":
if choice == "1":
id_choice = input("What would you like your account to be named?: ")
bal_choice = float(input("How much money would you like to deposit?(USD): "))
AccManager.create_account(ID = id_choice,bal = bal_choice)
Menu()
elif choice == "2":
acc_choice = input("What account would you like to access?(ID only, please): ")
AccManager.get_account(acc_choice)
print(acc_choice)
Menu()
答案 0 :(得分:3)
您的Account
个对象实际上似乎没有ID
个属性;相反,他们有id
个属性。 Python区分大小写;尝试将if account.ID == ID
更改为if account.id == ID
。
编辑:
在第一次不匹配后你也会回来。您需要从else
块中删除一级缩进,以便首先完成整个循环,事实上,您的else
块甚至不应该是else
块,因为你实际上并没有匹配if
;只有当帐户的无与给定ID匹配时,该方法才会失败。
编辑2:
此外,您实际上并没有将get_account()
的返回值分配给任何内容,因此它已丢失。我不确定你期望在那里发生什么。
答案 1 :(得分:0)
错误在于第31行和第35行。您已经写了“id”而不是“ID”。将这两件事充分资本化:
class Account(object):
"""An interactive bank account."""
wallet = 0
# Initial
def __init__(self, ID, bal):
print("A new account has been created!")
self.ID = ID
self.bal = bal
def __str__(self):
return "|Account Info| \nAccount ID: " + self.ID + "\nAccount balance: $" + self.bal
如果代码在此之后有效,请告诉我们。