0

I have created a simple class to manage tree of related objects:

class node(object):
    children = list([])

    def __init__(self, ID, *children):
        self.ID = ID
        for c in children:
            self.children.append(c)

    def add(self, *children ):
        for c in children:
            self.children.append(c)

    def __str__(self):
        return self.ID
    def __repr__(self):
        print self.ID, len(self.children)


root = node('1')
root.add( node('1.1', node('1.1.1')),
          node('1.2'))

for c in root.children:
    print c

I'm getting:

1.1.1
1.1
1.2

However I'm expecting just 1.1 and 1.2. What is my mistake?

thanks, Dmitry

DmitrySemenov
  • 9,204
  • 15
  • 76
  • 121

2 Answers2

3

self.children is referring to node.children, which is a class variable. There is only a single instance of your list that is shared across all instances of the class.

You need to make it an instance variable:

class Node(object):
    def __init__(self, id, *children):
        self.children = []

Also, __str__ and __repr__ should return strings that follow a certain format.

Community
  • 1
  • 1
Blender
  • 289,723
  • 53
  • 439
  • 496
  • Thank you Bender, what do you mean that __repr__ should return in certain format? My understanding is that it is used when you print the class, so the representation output is totally on dev and doesn't follow specific style. Did I miss something? I'm new to Python – DmitrySemenov Aug 03 '13 at 04:36
  • @DmitrySemenov: This'll be helpful: http://stackoverflow.com/questions/1436703/difference-between-str-and-repr-in-python – Blender Aug 03 '13 at 05:10
1

Place children = list([]) inside the __init__ method like this:

def __init__(self, ID, *children):
        self.ID = ID
        self.children = []
        for c in children:
            self.children.append(c)
mshsayem
  • 17,557
  • 11
  • 61
  • 69