程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

On the strange phenomenon of Python objects

編輯:Python

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

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved