Python Stack Corruption?

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!

+4
source share
2 answers

The children variable was declared as a class level variable, so it is shared among all instances of your Node s. You need to declare an instance variable by setting it in the initializer.

 class Node: #children = [] # not here... parent = 0 # might want to rethink where you initialize these visited = 0 cost = 0 position = (0, 0) leaf = 0 def __init__(self, parent, pos): self.parent = parent self.position = pos self.children = [] # ...but here def addChild(self, node): self.children += [node] 
+6
source

You created the "children" attribute of the class, which means that it is shared between all the objects in this class.

Instead, initialize it in the init method of the class.

 def __init__(self): self.children = [] ... 
+2
source

Source: https://habr.com/ru/post/1387910/


All Articles