[問題] Class內使用list的問題

看板Python作者 (Marco)時間3年前 (2021/04/13 00:03), 編輯推噓2(204)
留言6則, 4人參與, 3年前最新討論串1/1
各位大大好 請問class內是否可以各個物件使用各自的list呢? 我發現 two.thelist 會出現'10',但是實際append在one 請問原因是什麼呢? 要如何各自使用各自的list呢?(one & two 擁有不同的thelist) 請大大指點迷津! 感激不盡~ e.g. class class1(): theint = -1 thelist=[] def __init__(self, A, B): print(A) self.theint = A self.thelist.append(B) one = class1(123) two = class1(456) one.thelist.append(10) one.thelist >> Out: [456, 789, 10] two.thelist >> Out: [456, 789, 10] -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 114.44.75.200 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1618243395.A.F6C.html

04/13 00:14, 3年前 , 1F
你這邊建立class 要給兩個參數 你只給一個直接報錯吧
04/13 00:14, 1F

04/13 00:55, 3年前 , 2F
thelist放在__init__裡面賦值
04/13 00:55, 2F

04/13 00:56, 3年前 , 3F
簡單說就是刪掉thelist = []那行
04/13 00:56, 3F

04/13 08:07, 3年前 , 4F
你打印出來的是同一個類屬性thelist,就跟你打印the
04/13 08:07, 4F

04/13 08:07, 3年前 , 5F
int都是-1一樣
04/13 08:07, 5F

04/13 10:28, 3年前 , 6F
thelist 放的位置錯了,要放在__init()__ 區塊
04/13 10:28, 6F
文章代碼(AID): #1WT6z3zi (Python)
文章代碼(AID): #1WT6z3zi (Python)