Python检查帐户模拟器

时间:2013-04-25 14:33:21

标签: python oop python-3.x

我一直在使用python 3.0中的OOP程序来模拟一个支票帐户,我遇到了一个我无法弄清楚的错误。这是:在程序的主要部分,我给了 用户多个选项,例如退出,取款,存款和创建新帐户。当用户选择“创建新帐户”时,程序创建一个对象,变量名必须是另一个变量,我不知道如何从一个标有变量的对象访问属性。基本上我要问的是,怎么做我将变量名称变为变量,以便计算机可以跟踪它并使用它来访问对象的属性? 这是我到目前为止的程序(如果有帮助的话?):

class Checking(object):
    """a personal checking acount"""

    def __init__(self , name, balance):
        print("a new checking acount has been created")
        self.name = name
        self.balance = balance


    def __str__(self):
        rep = "Balance Object\n"
        rep += "name of acount" + self.name + "\n"
        rep += "balance is " + self.balance + "\n"
        return rep


    def display(self):
        print("\nyour acount name is ",self.name)
        print("your balance is",self.balance)


    def deposit(self):
        amount = int(input("\nplease enter the amount of money you wish to diposit"))
        self.balance += amount
        print("\nthe balance of 'chris' is ", self.balance)

    def withdraw(self):
        amount = int(input("\nplease enter the amount you wish to withdraw "))
        while amount > self.balance:
            print("is an invalid amount")
            amount = int(input("\nplease enter the amount you wish to withdraw "))
        self.balance -= amount
        print("\nthe balance of 'chris' is ", self.balance)






    answer = None

    while answer != "0":
        answer = input("""what action would you like to take?
        0 exit
        1 deposit
        2 withdraw
        3 add an acount""")
        if answer == "1":
            input("ener your PIN").deposit()
        if answer == "2":
            input("enter your PIN ").withdraw()
        if answer == "3":
            input("enter num") = Checking(name = input("\nwhat do you want your acount name to be?"), balance = 0)
            input("enter you PIN").display()
            print(Checking)

    input("\n\npress enter to exit")

1 个答案:

答案 0 :(得分:0)

使用字典;将帐户存储在accounts字典中,并将帐号作为密钥:

accounts = {}

# ...
if answer == 3:
    account_number = input("enter num")
    account_name = input("\nwhat do you want your acount name to be?")
    accounts[account_number] = Checking(name=account_name, balance=0)

现在您可以列出用户拥有的所有帐户,例如:

for account_number, account in accounts.items():
    print('Account number: {}, account name: {}'.format(account_number, account.name))

对于可变数量的项目使用局部变量是完全相同的,这绝不是一个好主意。在这种情况下,请使用列表或词典。