I am relatively new to python (but not programming) and I cannot explain the following behavior. It looks like the variable (list "children" in my example) from one object ("child") gets overwritten the value for this variable in a completely different object ("node"). To give some context, I'm trying to create a simple Node class for use in a tree structure. Node has children and a parent (all other nodes).
I cannot understand why child.children gets the same value as node.children. Somehow they refer to the same data? What for? Code and output:
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 a child), although I only updated node.children. Thanks for any help!
source share