如何在多个类中访问列表中的类实例?

0 投票
2 回答
729 浏览
提问于 2025-04-17 20:17

我是一名初学编程的程序员,正在制作一个模拟银行的程序,这个程序可以让用户管理多个银行账户,比如存取现金、创建账户、获取汇率等等。目前,我正在尝试访问我类中的一组实例,这些实例都是我的账户类的对象。账户管理类负责管理这些账户对象,并在用户需要输入时帮助组织它们。现在,我正在尝试模拟菜单上的第三个选项,这个选项可以获取用户选择的账户信息(用户必须手动输入他们账户的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()

2 个回答

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

请告诉我们修改后代码是否能正常运行。

3

你的 Account 对象似乎并没有 ID 属性,而是有 id 属性。Python 是区分大小写的,所以你可以把 if account.ID == ID 改成 if account.id == ID

编辑:

你在第一次不匹配的时候就返回了,这样不太对。你需要把 else 代码块的缩进减少一级,这样才能遍历完整个循环。实际上,你的 else 代码块也不应该是 else,因为你并没有和任何 if 进行匹配;这个方法应该只有在没有任何账户匹配给定的 ID 时才会失败。

编辑 2:

另外,你并没有把 get_account() 的返回值赋给任何东西,所以这个值就丢失了。我不太确定你希望在这里发生什么。

撰写回答