1

I am trying to write a node class to create a tree structure. There seems to be some problem when I'm trying to add a child node to the root node with the method "addChild" because the child node appears to have itself in its children list. I couldn't figure out why, so any help is appreciated.

class node(object):
    def __init__(self, name, x, y, children = []):
        self.name = name
        self.children = children
        self.x = x
        self.y = y

    def addChild(self): 
        b=node('b', 5, 5)
        self.children.append(b)
        return

root=node('a',0.,0.)
print root.children 

root.addChild() 

print root.children
print root.children[0].children

Yields:

[<__main__.node object at 0x7faca9f93e50>]
[<__main__.node object at 0x7faca9f93e50>]

Whereas the second "print" line should have returned an empty array.

yam
  • 1,383
  • 3
  • 15
  • 34
  • 1
    Every node is referencing the same list. See http://stackoverflow.com/questions/1132941/least-astonishment-in-python-the-mutable-default-argument – Tim Oct 12 '13 at 02:50

1 Answers1

4

The default parameter value children = [] assigns a single list object to the __init__ function that is then used on every call all children. This is a common mistake. Instead, create children in the __init__ function itself:

class node(object):
    def __init__(self, name, x, y, children=None):
        self.name = name
        self.children = [] if children is None else children
        self.x = x
        self.y = y
 # ...
Community
  • 1
  • 1
phihag
  • 278,196
  • 72
  • 453
  • 469