In the following code, I understand that the print of tree
(named in the code) and parent
(named in the code) should not be the same. But I do not understand, why the tree
is always updating according to the updating of parent
?
(This question continues the last question here)
Code:
class node(object):
def __init__(self, value):
self.value = value
self.children = []
def __repr__(self, level=0):
ret = "\t"*level+repr(self.value)+"\n"
for child in self.children:
ret += child.__repr__(level+1)
return ret
def add(self, nod):
self.children.append(nod)
list_0 = ['AA', 'BB', 'CC', 'DD']
tree = parent = node(list_0[0])
i=1
while i<len(list_0):
current_node = node(list_0[i])
parent.add(current_node)
parent = current_node
i+=1
print(tree)
print(parent)
Output:
'AA'
'BB'
'CC'
'DD'
'DD'
In the code, it is obvious that the parent
is re-initialized every time in the loop, but according to my understanding, while the parent
is updating, the tree
should not be updated accordingly. Because once the parent
is re-initialized in the loop, it then does not have the same id(maybe address) with the tree
anymore, then the tree
will not be changed according to the parent
.
Question:
why the
tree
is still updating according to theparent
even theid(parent)
is changed every time in the loop?how the
tree
is linking to theparent
which is inside the loop? e.g.,node[1]
,node[2]
.(update)
Appreciate any comment or explanation, thanks in advance!