在Python中附加列表

use*_*900 2 python oop list

我正在尝试创建一个方法,允许类的每个实例成为彼此的"邻居".如果实体A将B添加为邻居,则B在A的neighbor_list中.但是,如下面的输出所示,B会自动添加到B的邻居列表中,这不是所需的行为 - B的邻居列表应为空.有什么想法吗?

输出:

 a's neighbor list element: b
 b's neighbor list element: b
Run Code Online (Sandbox Code Playgroud)

码:

 class Entities:
     neighbor_list = []
     name = ''

     def __init__(self,name):
         self.name = name

     def add (self, neighbor):
         self.neighbor_list.append(neighbor)  

 a = Entities ('a')
 b = Entities ('b')
 a.add(b)
 print "a's neighbor list element: %s" % a.neighbor_list[0].name
 print "b's neighbor list element: %s" % b.neighbor_list[0].name
Run Code Online (Sandbox Code Playgroud)

jon*_*rpe 6

创建neighbor_list一个实例,而不是类,属性:

class Entities(object):
    # not here
    def __init__(self, name):
        self.name = name
        self.neighbor_list = [] # here
Run Code Online (Sandbox Code Playgroud)

在实例方法之外定义的类属性由类的所有实例共享.