0

我创建了一个简单的类来管理相关对象的树:

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

我越来越:

1.1.1
1.1
1.2

但是我只期待 1.1 和 1.2。我的错误是什么?

谢谢,德米特里

4

2 回答 2

3

self.children指的是node.children,它是一个类变量。您的列表中只有一个实例在类的所有实例之间共享。

您需要将其设为实例变量:

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

此外,__str__并且__repr__应该返回遵循某种格式的字符串。

于 2013-08-03T01:27:22.383 回答
1

像这样放置children = list([])__init__方法中:

def __init__(self, ID, *children):
        self.ID = ID
        self.children = []
        for c in children:
            self.children.append(c)
于 2013-08-03T01:30:17.340 回答