简体   繁体   English

有多个类时,如何访问列表中的类实例?

[英]How do I access a class instance in a list when there is multiple classes?

I'm a beginning programmer who is building a program that simulates a bank with multiple bank accounts that a user can withdraw/deposit cash, create accounts, get exchange rates, etc. Currently, I'm trying to access a group of instances in my class that are all objects of my account class. 我是一名初级程序员,正在构建一个程序来模拟具有多个银行帐户的银行,用户可以在其中提取/存款现金,创建帐户,获取汇率等。目前,我正在尝试访问中的一组实例我的班级是我的帐户班级的所有对象。 The Account Manager class is responsible for managing these account objects and helping to organize them when user input is required. 客户经理类负责管理这些客户对象,并在需要用户输入时帮助组织它们。 Right now, I'm trying to simulate my 3rd option on my menu which gets info on the account of a user's choice(they must manually put the ID of their account in in order to retrieve information on it, withdraw/deposit cash, etc.). 现在,我正在尝试在菜单上模拟我的第三个选项,该选项可获取有关用户选择的帐户的信息(他们必须手动输入其帐户的ID才能检索该帐户上的信息,提取/存入现金等) )。 Although I've managed to store all of these class instances in a list, I can't seem to use my get_account method to retrieve these for use. 尽管我已经设法将所有这些类实例存储在列表中,但似乎无法使用get_account方法来检索这些实例以供使用。 I'll post all of my code below. 我将在下面发布所有代码。 If you see anything else that is out of place, feel free to let me know. 如果您发现其他任何不正常的地方,请随时告诉我。 Code: 码:

# 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()

Your Account objects don't actually seem to have ID attributes; 您的Account对象实际上似乎没有ID属性; instead, they have id attributes. 相反,它们具有id属性。 Python is case-sensitive; Python区分大小写; try changing if account.ID == ID to if account.id == ID . 尝试将if account.ID == ID更改为if account.id == ID

EDIT: 编辑:

You are also returning after the very first mismatch. 您也将在第一次不匹配后返回。 You need to remove one level of indentation from your else block so that you get through the entire loop first, and in fact, your else block shouldn't even be an else block, since you're not actually matching an if ; 您需要从else块中删除一个缩进级别,以使您首先遍历整个循环,实际上,您的else块甚至else应该是else块,因为实际上并没有匹配if ;。 the method should only fail if none of the accounts match the given ID. 仅当没有一个帐户与给定ID匹配时,该方法才会失败。

EDIT 2: 编辑2:

Also, you're not actually assigning the return value from get_account() to anything, so it's lost. 同样,您实际上并没有将get_account()的返回值分配给任何东西,因此它丢失了。 I'm not exactly sure what you expect to happen there. 我不确定您在那里会发生什么。

The error lies in lines 31 and 35. You have written "id" instead of "ID". 该错误位于第31和35行。您编写的是“ id”而不是“ ID”。 Fully capitalize those two things such that: 将这两件事完全大写:

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

Please let us know if the code works after that. 之后,请告诉我们代码是否有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM