Python,子项列表

Python, List of Children

我想在 Python 3.8.10 中生成一个 parent/child 数据结构。 [GCC 9.3.0] on linux 代码很简单:

class Member(object):
    name = "xxx"
    parent = None
    children = []
    
    def __init__(self, name):
        object.__init__(self)
        self.name = name
    
    def setParent(self,p):
        self.parent = p
        
    def addChild(self,ch):
        self.children.append(ch)
        ch.setParent(self)
        
    def myRelatives(self):
        str = "I am {0}, my parent is {1} my children are:".format(self.name,self.parent.name if self.parent is not None else "--")
        print(str)

        for ch in self.children:
            print("   {0}".format(ch.name))
       

if __name__ == '__main__':
    A = Member("A")
    B = Member("B")
    C = Member("C")
    D = Member("D")
    
    A.addChild(B)
    B.addChild(C)
    C.addChild(D)
    
    A.myRelatives()
    B.myRelatives()
    C.myRelatives()
    D.myRelatives()

我预计:

I am A, my parent is -- my children are:
   B
I am B, my parent is A my children are:
   C
I am C, my parent is B my children are:
   D
I am D, my parent is C my children are:

但是我的输出是:

I am A, my parent is -- my children are:
   B
   C
   D
I am B, my parent is A my children are:
   B
   C
   D
I am C, my parent is B my children are:
   B
   C
   D
I am D, my parent is C my children are:
   B
   C
   D

似乎 'self.children' 在所有实例中都用作相同的变量。为什么以及如何修复?

谢谢, 伯恩德

您需要在 __init__ 函数中设置属性 nameparentchildren,例如像这样:

    def __init__(self, name):
        super().__init__(self)
        self.name = name
        self.parent = None
        self.children = list()

那么应该可以了。

编辑: 添加了@chepner 建议的改进。