# On the strange phenomenon of Python objects

2022-06-24 07:20:20

Declared a `node` class ：

``````class Node:
feat = -1
child = []
label = -1

def __init__(self, feat, label):
self.feat = feat
self.label = label
``````

Create two `node`, And will `node2` Put in `node1` Medium `child` in ：

``````node1 = Node(2, 0)
node2 = Node(3, 1)

print(node2.feat, node2.label)
node2.change(9)
node1.child.append(node2)
print(len(node1.child))
print(node1.child[0].feat, node1.child[0].label)

Output results :
3 1
1
9 1
``````

When redefining two different initial values `node`, Same operation , But found `node1` Of `child` The number becomes 2

``````node1 = Node(2, 2)
node2 = Node(6, 1)

print(node2.feat, node2.label)
node2.change(15)
node1.child.append(node2)
print(len(node1.child))
print(node1.child[0].feat, node1.child[0].label)
``````

Traverse `node1.child` After the discovery , Two `node2` It's all in it ：

``````for i in range(len(node1.child)):
print(node1.child[i].feat, node1.child[i].label)

Output results :
9 1
15 1
``````