Problem Description
Just ask a question in the dormitory, simply said that the programming encountered the following situation:
Class Node (object):
def __init__ (self, childrenlist=[], name = '. '):
self.name = name
self.childrenlist = Ch Ildrenlist
A = node (name = ' WJ ')
B = node ()
a.childrenlist.append (1)
print (a.childrenlist)
Print (b.childrenlist)
The output is as follows:
[1]
[1]
reason
Strangely, the assignment of instance a causes the variable childrenlist in B to change.
Intuitively, it should be a function parameter assignment is a value or a reference to pass the problem, of course, in essence or the value of the transfer, but the assignment object is variable or immutable problem.
So, to test:
Class Node (object):
def __init__ (self, childrenlist=[], name = '. '):
self.name = name
self.childrenlist = Ch Ildrenlist
Print ("Childrenlist", ID (self.childrenlist))
print ("name", ID (self.name))
a = Node (name = ' WJ ')
B = Node ()
a.childrenlist.append (1)
print (a.childrenlist)
print (b.childrenlist)
Results
Childrenlist 2754369477512
name 2754369477232
childrenlist 2754369477512
name 2754335175152
As you can see, the name string differs in memory locations in two instances, but the childrenlist is the same, and the result in 1 appears. Modify
The simplest way to assign a value directly by using self.childrenlist=[is to not use the value in the parameter.
A better way to use Python's deep copy.
Import copy
class Node (object):
def __init__ (self, childrenlist=[], name = '. '):
self.name = name
Self.childrenlist = Copy.deepcopy (childrenlist)
a = node (name = ' WJ ')
B = node ()
a.childrenlist.append (1) C7/>print (a.childrenlist)
print (b.childrenlist)
In this way, the childrenlist in the generated instance will point to different units.