作者xb1015 (Marco)
看板Python
標題[問題] Class內使用list的問題
時間Tue Apr 13 00:03:13 2021
各位大大好
請問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
→ dogppatrick: 你這邊建立class 要給兩個參數 你只給一個直接報錯吧 04/13 00:14
推 sherees: thelist放在__init__裡面賦值 04/13 00:55
→ sherees: 簡單說就是刪掉thelist = []那行 04/13 00:56
推 aidansky0989: 你打印出來的是同一個類屬性thelist,就跟你打印the 04/13 08:07
→ aidansky0989: int都是-1一樣 04/13 08:07
→ leolarrel: thelist 放的位置錯了,要放在__init()__ 區塊 04/13 10:28