如何避免在实例之间共享类数据? [英] How to avoid having class data shared among instances?
本文介绍了如何避免在实例之间共享类数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要的是这种行为:
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]
当然,当我打印时真正发生的是:
Of course, what really happens when I print is:
print(x.list) # prints [1, 2, 3, 4]
print(y.list) # prints [1, 2, 3, 4]
显然他们正在a
类中共享数据.我如何获得单独的实例来实现我想要的行为?
Clearly they are sharing the data in class a
. How do I get separate instances to achieve the behavior I desire?
推荐答案
你想要这个:
class a:
def __init__(self):
self.list = []
在类声明中声明变量使它们成为类"成员而不是实例成员.在 __init__
方法中声明它们可确保在对象的每个新实例旁边创建成员的新实例,这是您正在寻找的行为.
Declaring the variables inside the class declaration makes them "class" members and not instance members. Declaring them inside the __init__
method makes sure that a new instance of the members is created alongside every new instance of the object, which is the behavior you're looking for.
这篇关于如何避免在实例之间共享类数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文