Re: [問題] 基礎 list append

看板Python作者 (用口頭禪區分年記)時間15年前 (2009/11/13 18:00), 編輯推噓1(101)
留言2則, 2人參與, 最新討論串2/2 (看更多)
※ 引述《zha1 (zha1)》之銘言: : args.append(0) : print args : [0] : [1, 0] : >>> a() : [0, 0] 為什麼這裡, a() 完會是 2 , 上面就一次了 .. 為什麼 1 不見了 . XD : [1, 2, 3, 4, 0] : [0, 0, 0] default parameters 只會evaluate 一次。 所以這裡你的 args 就好像 C語言裡的 static variable,就算function 已經 return 了, args的值還是存在著。 所以請你用以下的寫法: def a( arg = None): if arg == None : arg = [] arg.append(10) print arg FYI: http://docs.python.org/reference/compound_stmts.html Default parameter values are evaluated when the function definition is executed -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 140.112.30.45 ※ 編輯: timTan 來自: 140.112.30.45 (11/13 18:00) ※ 編輯: timTan 來自: 140.112.30.45 (11/13 18:01) ※ 編輯: timTan 來自: 140.112.30.45 (11/13 18:03) ※ 編輯: timTan 來自: 140.112.30.45 (11/13 18:11)

11/13 21:03, , 1F
所以指定Default parameter的值為immutable類型就可避免?
11/13 21:03, 1F

11/13 23:47, , 2F
上面說的一種解法,設定成None再另外assigsn是另一種解法
11/13 23:47, 2F
文章代碼(AID): #1A_Iu-dL (Python)
文章代碼(AID): #1A_Iu-dL (Python)