如何避免实例之间共享类数据? [英] How do I avoid having class data shared among instances?
本文介绍了如何避免实例之间共享类数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想要的是这种行为:
class a:
list = []
y = a()
x = a()
x.list.append(1)
y.list.append b x.list.append(3)
y.list.append(4)
print x.list
[1,3]
print y.list
[2,4]
当然,我打印时真正发生的是: / p>
print x.list
[1,2,3,4]
print y.list
[1,2,3,4]
c $ c> a 。
解决方案
你想要这样:
class a:
def __init __(self):
self.list = []
声明类声明中的变量使它们成为类成员而不是实例成员。在 __ init __
方法中声明它们可以确保在对象的每个新实例的旁边创建一个新的成员实例,这是你正在寻找的行为。 p>
What I want is this behavior:
class a:
list=[]
y=a()
x=a()
x.list.append(1)
y.list.append(2)
x.list.append(3)
y.list.append(4)
print x.list
[1,3]
print y.list
[2,4]
of course, what really happens when I print is:
print x.list
[1,2,3,4]
print y.list
[1,2,3,4]
clearly they are sharing the data in class a
. how do I get separate instances to achieve the behavior I desire?
解决方案
You want this:
class a:
def __init__(self):
self.list = []
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屋!
查看全文