2013-04-25 128 views
0

我一直在Python 3.0中的OOP程序模擬一個支票帳戶,我遇到了一個我找不到的bug。這裏是:在該計劃的主要部分,我給了 用戶多個選項,如退出,提取,存款和創建新帳戶。當用戶選擇「創建新帳戶」時,程序創建一個對象,變量名稱必須是另一個變量,而我不知道如何從標有變量的對象訪問屬性。基本上我問的是,怎麼做我將一個變量名變爲變量,以便計算機可以跟蹤它並使用它來訪問對象的屬性? 這裏是程序我到目前爲止:Python檢查帳戶模擬器

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") 

回答

0

使用字典;(是否有幫助?)商店賬戶在accounts字典的acount號碼作爲重點:

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

使用局部變量對於數量可變的項目來說,這些都是一樣的,從來都不是一個好主意。在這種情況下,請使用列表或字典。

+0

非常感謝你 – vitruvianrockman 2013-04-25 14:40:47

+0

我真的不知道如何接受我只是點擊按鈕 – vitruvianrockman 2013-04-25 17:04:42

+0

然後我想通了 – vitruvianrockman 2013-04-25 17:05:01