書上的實作如下:
0;32m######################
def diplayInventory(inventory): #顯示字典用的函數
print("Inventory:")
item_total=0
for k,v in inventory.items():
print(str(v)+' '+k)
item_total=item_total+1
print("items number:"+str(item_total))
def addInventory(inventory,addItems):
#這邊是要練習寫的地方
inv={'rope':1,'劍':1,'gold coin':42,'dagger':1,'arrow':1}
dragonLoot=['超級劍','gold coin','arrow']
inv=addInventory(inv,dragonLoot)
diplayInventory(inv)
######################
其中inv=addInventory(inv,dragonLoot)的參照部分我不明白
因為函數如果這樣寫就可以:
######################
def addInventory(inventory,addItems):
for i in range(len(addItems)):
inv.setdefault(addItems[i],0) #串列名稱key寫入inv
inventory[addItems[i]]=inventory[addItems[i]]+1 #增加串列名稱i到字典內的數量
inv={'rope':1,'劍':1,'gold coin':42,'dagger':1,'arrow':1} #倉庫
dragonLoot=['超級劍','gold coin','arrow']
addInventory(inv,dragonLoot)
diplayInventory(inv)
######################
書裡面卻是用參照的方式,但diplayInventory函數要傳入的應該是字典
參照的對象卻是一個把字典參照了函數,那這樣就會顯示錯誤訊息:
Traceback (most recent call last):
File "C:\Dropbox\Tools\python code\python.py", line 20, in <module>
diplayInventory(inv)
File "C:\Dropbox\Tools\python code\python.py", line 4, in diplayInventory
for k,v in inventory.items():
AttributeError: 'NoneType' object has no attribute 'items'
想請教如果是按書裡的寫法應該是怎麼解?