This is basically the same problem discussed in here.
Surprisingly? when you define class, Python interpreter execute class field. And then if you create a new instance of the class, class field is not executed. So class field is executed once only when you define class. Like:
class someClass:
someVar = 0 #<---This class field is executed once
def __init__(self):
pass
OK. Now you defined class. Next you create new instance of the class. Like:
instance1 = someClass()
instance2 = someClass()
This will create new memory and copy data from someClass
.
Now instance1
and instance2
do not share memory space. They have own independent memory space. So instance1.someVar
and instance2.someVar
has different memory space. But 0
in instance1.someVar
and 0
in instance2.someVar
are completely same object(0
is on same memory space). You can ensure it doing like:
print id(instance1.someVar)==id(instance2.someVar)
So you can find 0
is completely same object.
This is not the only case when someClass.someVar = 0
. Same thing will happen when you use []
replacement of 0
.
Back to your code. You can simply occur your problem doing like this:
class test:
group = []
def __init__(self,name):
self.name = str(name)
test0 = test(0)
test1 = test(1)
test0.group.append(100)
print test0.group
print test1.group
#[100]
#[100]
#will be printed
This is because test0.group
and test1.group
point same object. Like:
+-----------+
|test0.group|------+
+-----------+ |
v
+-------+
| [] |
+-------+
^
+-----------+ |
|test1.group|------+
+-----------+
When you executed test0.group.append(100)
, it becomes like:
+-----------+
|test0.group|------+
+-----------+ |
v
+-------+
| [100] |
+-------+
^
+-----------+ |
|test1.group|------+
+-----------+
Also you can set another object. Like:
test1.group = "123"
Then test1.group
becomes like:
+-----------+
|test0.group|------+
+-----------+ |
v
+-------+
| [100] |
+-------+
+-----------+ +-----+
|test1.group|------>|"123"|
+-----------+ +-----+
Sorry for my bad English. I hope it helps. :)