- Python面向對象編程:構建游戲和GUI
- (美)艾維·卡爾布
- 993字
- 2023-06-29 17:17:46
1.2.5 實現4:使用列表的多個賬戶
為了更方便支持多個賬戶,在代碼清單1-5中,我們將使用列表表示數據。程序的這個版本使用了3個列表——accountNamesList、accountPasswordsList和accountBalancesList。
代碼清單1-5:使用并行列表的銀行模擬程序(文件: Bank4_N_Accounts.py)
# Non-OOP Bank
# Version 4
# Any number of accounts - with lists
? accountNamesList = []
accountBalancesList = []
accountPasswordsList = []
def newAccount(name, balance, password):
global accountNamesList, accountBalancesList, accountPasswordsList
? accountNamesList.append(name)
accountBalancesList.append(balance)
accountPasswordsList.append(password)
def show(accountNumber):
global accountNamesList, accountBalancesList, accountPasswordsList
print(‘Account’, accountNumber)
print(‘ Name’, accountNamesList[accountNumber])
print(‘ Balance:’, accountBalancesList[accountNumber])
print(‘ Password:’, accountPasswordsList[accountNumber])
print()
def getBalance(accountNumber, password):
global accountNamesList, accountBalancesList, accountPasswordsList
if password != accountPasswordsList[accountNumber]:
print(‘Incorrect password’)
return None
return accountBalancesList[accountNumber]
--- snipped additional functions ---
# Create two sample accounts
? print(“Joe’s account is account number:”, len(accountNamesList))
newAccount(“Joe”, 100, ‘soup’)
? print(“Mary’s account is account number:”, len(accountNamesList))
newAccount(“Mary”, 12345, ‘nuts’)
while True:
print()
print(‘Press b to get the balance’)
print(‘Press d to make a deposit’)
print(‘Press n to create a new account’)
print(‘Press w to make a withdrawal’)
print(‘Press s to show all accounts’)
print(‘Press q to quit’)
print()
action = input(‘What do you want to do? ‘)
action = action.lower() # force lowercase
action = action[0] # just use first letter
print()
if action == ‘b’:
print(‘Get Balance:’)
? userAccountNumber = input(‘Please enter your account number: ‘)
userAccountNumber = int(userAccountNumber)
userPassword = input(‘Please enter the password: ‘)
theBalance = getBalance(userAccountNumber, userPassword)
if theBalance is not None:
print(‘Your balance is:’, theBalance)
--- snipped additional user interface ---
print(‘Done’)
在程序的開頭,將3個列表設置為空列表(?)。為了創建一個新賬戶,將合適的值追加到每個列表(?)。
因為現在要處理多個賬戶,所以使用了銀行賬戶號碼這個基本概念。每當用戶創建賬戶的時候,代碼就對一個列表使用len()函數,并返回該數字,作為該用戶的賬號(??)。為第1個用戶創建賬戶時,accountNamesList的長度是0。因此,第1個賬戶的賬號是0,第2個賬戶的賬號是1,以此類推。和真正的銀行一樣,在創建賬戶后,要執行任何操作(如存款或取款),用戶必須提供自己的賬號(?)。
但是,這里的代碼仍然在使用全局數據,現在有3個全局數據列表。
想象一下在電子表格中查看這些數據,如表1-1所示。
表1-1 數據表

這些數據作為3個全局Python列表進行維護,每個列表代表這個表格中的一列。例如,從突出顯示的列中可以看到,全部密碼作為一個列表放到一起。用戶的姓名放到另外一個列表中,余額也放到一個列表中。當采用這種方法時,要獲取關于一個賬戶的信息,需要使用一個公共的索引值訪問這些列表。
雖然這種方法可行,但非常麻煩。數據沒有以一種符合邏輯的方式進行分組。例如,把所有用戶的密碼放到一起并不合理。另外,每次為一個賬戶添加一個新特性(如地址或電話號碼)時,就需要創建并訪問另外一個全局列表。
與這種方法相反,我們真正想要的分組是代表這個電子表格中的一行的分組,如表 1-2所示。
表1-2 數據表

這樣一來,每一行代表與一個銀行賬戶關聯的數據。雖然數據一樣,但這種分組是代表賬戶的一種更加自然的方式。