[問題] default value for arguments..

看板Python作者 (一人吃二人補)時間15年前 (2009/01/28 03:17), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串1/4 (看更多)
hi, all: 我在國外的某個blog上看到一篇文章: http://tinyurl.com/8t73xp 裡面的一段程式碼: >>> class Foo(object): ... def __init__(self, name='', stuff=[]): ... self.name = name ... self.stuff = stuff ... ... def add_stuff(self, gadget): ... self.stuff.append(gadget) ... >>> f = Foo() >>> f.add_stuff('tree') >>> f.stuff ['tree'] >>> g = Foo() >>> g.stuff ['tree'] 這結果跟我之前學的OOP有些不同..沒實際執行一次,我會以為g.stuff應該是[] 雖然它底下有說原因: What happens here is that default values for arguments are created by Python only once per each function/method, at the time of its definition. 小的是python新手,看不太懂真正原因,不知道可否有前輩幫忙解說一下呢? 感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 220.131.240.242
文章代碼(AID): #19Vrs-uW (Python)
文章代碼(AID): #19Vrs-uW (Python)