[問題] 新手問題,定義函數的問題
書上的實作如下:
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'
想請教如果是按書裡的寫法應該是怎麼解?
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 218.187.101.135 (臺灣)
※ 文章網址: https://www.ptt.cc/bbs/Python/M.1591285642.A.B15.html
推
06/05 00:09,
5年前
, 1F
06/05 00:09, 1F
→
06/05 01:06,
5年前
, 2F
06/05 01:06, 2F
→
06/05 09:20,
5年前
, 3F
06/05 09:20, 3F
謝謝,學到新寫法
→
06/05 09:21,
5年前
, 4F
06/05 09:21, 4F
其實我的想寫法也是用addInventory(inv,dragonLoot),也可以運作
只是書上的範例就是寫要用:inv=addInventory(inv,dragonLoot)
所以才疑惑這樣要如何寫,這只是書上一個實作專題,而且還沒給答案=.=
→
06/05 11:40,
5年前
, 5F
06/05 11:40, 5F
其實書上也沒有寫這題是要考甚麼觀念=.=
→
06/05 12:21,
5年前
, 6F
06/05 12:21, 6F
恩恩,我自己想的版本也是inv=可以拿掉就可運作,但我不懂的就是書上為什麼這樣寫
→
06/05 12:21,
5年前
, 7F
06/05 12:21, 7F
→
06/05 12:23,
5年前
, 8F
06/05 12:23, 8F
→
06/05 12:25,
5年前
, 9F
06/05 12:25, 9F
這個就比較深了,我好好琢磨琢磨
※ 編輯: kslman (218.187.82.118 臺灣), 06/05/2020 23:06:27
→
06/06 00:29,
5年前
, 10F
06/06 00:29, 10F
→
06/06 00:29,
5年前
, 11F
06/06 00:29, 11F
→
06/06 00:29,
5年前
, 12F
06/06 00:29, 12F
→
06/06 00:29,
5年前
, 13F
06/06 00:29, 13F
→
06/06 00:29,
5年前
, 14F
06/06 00:29, 14F
→
06/06 00:29,
5年前
, 15F
06/06 00:29, 15F
→
06/06 00:55,
5年前
, 16F
06/06 00:55, 16F
→
06/06 01:24,
5年前
, 17F
06/06 01:24, 17F
→
06/06 01:24,
5年前
, 18F
06/06 01:24, 18F
→
06/06 01:24,
5年前
, 19F
06/06 01:24, 19F
→
06/06 01:24,
5年前
, 20F
06/06 01:24, 20F
推
06/07 04:09,
5年前
, 21F
06/07 04:09, 21F
→
06/07 04:10,
5年前
, 22F
06/07 04:10, 22F
→
06/07 04:11,
5年前
, 23F
06/07 04:11, 23F
→
06/07 04:13,
5年前
, 24F
06/07 04:13, 24F
→
06/08 22:12,
5年前
, 25F
06/08 22:12, 25F
Python 近期熱門文章
PTT數位生活區 即時熱門文章