I’m relatively new to python (but not to programming), and I can’t explain the following behavior. It appears that a variable (the list “children” in my example) from one object (“child”) is getting overwritten by the value for that variable in a completely different object (“node”). To give some context, I’m trying to create a simple Node class to use in a tree structure. The node has children and a parent (all other nodes).
I can’t figure out why child.children gets the same value as node.children. Are they somehow referencing the same data? Why? Code and output follows:
class Node:
children = []
parent = 0
visited = 0
cost = 0
position = (0, 0)
leaf = 0
def __init__(self, parent, pos):
self.parent = parent
self.position = pos
def addChild(self, node):
self.children += [node]
node = Node(0, (0,0))
child = Node(node, (3,2))
node.addChild(child)
print "node: ",
print node
print "node.childen: ",
print node.children
print "child: ",
print child
print "child.children",
print child.children
Output:
node: <__main__.Node instance at 0x414b20>
node.childen: [<__main__.Node instance at 0x414b48>]
child: <__main__.Node instance at 0x414b48>
child.children [<__main__.Node instance at 0x414b48>]
As you can see, both node.children and child.children have the same value (a list containing child) even though I only updated node.children. Thanks for any help!
The
childrenvariable was declared as a class-level variable so it is shared amongst all instances of yourNodes. You need to declare it an instance variable by setting it in the initializer.