0

I've been completely perplexed by a bug in a larger system. Consider this class (each node maintains a pointer to its parent and a list of its children):

class Node:
    children = []

    def __init__(self, parent):
        self.contents = dict()
        self.parent = parent

        if parent is not None:
            print self.children
            print parent == self
            parent.children.append(self)
            print self.children

Running this:

foo1 = Node(None)
foo2 = Node(foo1)

Mysteriously returns this:

[]
False
[<__main__.Node instance at 0x10051f128>]

How does this make any sense whatsoever? Why is the second node's children not empty? Perhaps I'm missing a basic understanding of a concept related to how Python passes references around.

David Chouinard
  • 6,466
  • 8
  • 43
  • 61

1 Answers1

3

You've defined children as a class variable. It's shared by all members of the class. Move the declaration into __init__ and change it to self.children = [] and you'll get the result you expect.

YXD
  • 31,741
  • 15
  • 75
  • 115