[問題] 新手問題,定義函數的問題

作者: kslman   2020-06-04 23:47:20
書上的實作如下:
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'
想請教如果是按書裡的寫法應該是怎麼解?
作者: TuCH (謬客)   2020-06-05 00:09:00
return inventory
作者: kslman   2020-06-05 01:06:00
謝謝,所以在這邊其實inventory就是inv的參照,對嗎?
作者: stlevi811101 (cj84161)   2020-06-05 09:20:00
https://onlinegdb.com/Bk_h6Gwn8 這樣?也不用return吧猜你的問題是dict的global或是local的問題是嗎
作者: mychiux413 (小邱)   2020-06-05 12:21:00
inv=可以拿掉,你可以想像dict/list都是指標,str/int//float等都是值,所以dict/list都有一個.copy方法雖然傳指標效能比較好,但在大型專案上會盡量避免沒有效能考量的話,我會用return obj.copy()的方式去傳
作者: alvinlin (林矜業)   2020-06-06 00:29:00
其實你的用法才是參照吧。主程式有個變數inv所以函數要有return,沒有return時,Python 有一個預設return None。所以你的inv會變成None,所以就錯了。因為你的做法等於用inventory去修改了inv。所以你的inventory 參照了inv的記憶體位址,當你一修改inventory 後inv的值也跟著改了,這是樓上的意思。但這個例子和參不參照沒什麼關聯。
作者: kslman   2020-06-06 00:55:00
看懂了<(_ _)>
作者: alvinlin (林矜業)   2020-06-06 01:24:00
^^。但你原意應該是指「參數」。因為函數通常是重復使用的。就像print()。有時候函數還要給別人用,所以最好是不要不傳參數直接修改主程式,這樣你的函數只能在這個程式用,未來要寫成套件時就不方便了
作者: stlevi811101 (cj84161)   2020-06-07 04:09:00
https://onlinegdb.com/ry1luOK3U如果不想修改原有的字典 可以在函式內另建空字典update裝載原字典 最後再把獨立的inv_dict吐出來剛開始學python可以善用id() method去看變數地址
作者: kslman   2020-06-08 22:12:00
收到!
作者: salmon12706 (Ellen)   2020-06-29 16:16:00
工研院人工智慧課程推薦https://reurl.cc/4RDRaK

Links booklink

Contact Us: admin [ a t ] ucptt.com