简体   繁体   English

奇怪的Python类行为

[英]Strange Python class behavior

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. 但是我期望只有1.1和1.2。 What is my mistake? 我怎么了

thanks, Dmitry 谢谢,德米特里

self.children is referring to node.children , which is a class variable. self.children引用的是node.children ,它是一个类变量。 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. 同样, __str____repr__应该返回遵循某种格式的字符串。

Place children = list([]) inside the __init__ method like this: children = list([])放在__init__方法内,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM