相关疑难解决方法(0)

如何避免在实例之间共享类数据?

我想要的是这种行为:

class a:
    list = []

x = a()
y = a()

x.list.append(1)
y.list.append(2)
x.list.append(3)
y.list.append(4)

print(x.list) # prints [1, 3]
print(y.list) # prints [2, 4]
Run Code Online (Sandbox Code Playgroud)

当然,我打印时真正发生的是:

print(x.list) # prints [1, 2, 3, 4]
print(y.list) # prints [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)

显然,他们正在课堂上分享数据a.如何获得单独的实例来实现我想要的行为?

python class

133
推荐指数
5
解决办法
2万
查看次数

标签 统计

class ×1

python ×1