作者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://webptt.com/cn.aspx?n=bbs/Python/M.1618243395.A.F6C.html
1F:→ dogppatrick: 你这边建立class 要给两个参数 你只给一个直接报错吧 04/13 00:14
2F:推 sherees: thelist放在__init__里面赋值 04/13 00:55
3F:→ sherees: 简单说就是删掉thelist = []那行 04/13 00:56
4F:推 aidansky0989: 你打印出来的是同一个类属性thelist,就跟你打印the 04/13 08:07
5F:→ aidansky0989: int都是-1一样 04/13 08:07
6F:→ leolarrel: thelist 放的位置错了,要放在__init()__ 区块 04/13 10:28