在一个对象中更改变量将更新同一类的另一个对象的相同变量

时间:2020-01-27 10:06:29

标签: python class oop

我编写了一个Node类并创建了三个对象,当我在第一个对象中分配变量的值时,第二个对象的相同变量将被更新,第三个对象的相同。这是代码,

class Node:
    nodes_neighbour = []
    nodes_neighbour_loc = []

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

    def addNeighbours(self,neighbours):
        i = 0
        while(i < len(neighbours)):
            self.nodes_neighbour.append(neighbours[i])
            self.nodes_neighbour_loc.append(neighbours[i].location)

            i = i + 1

    def setCosts(self,g,f):
        self.g = g
        self.f = f



n1 = Node([10,10])
n2 = Node([50,10])
n3 = Node([90,10])

n1.addNeighbours([n2,n3])
print(n2.nodes_neighbour_loc)

正在打印, [[50,10],[90,10]]

出什么问题了? 在此先感谢:)

1 个答案:

答案 0 :(得分:1)

您的成员nodes_neighbournodes_neighbour_loc是该类的实例,并且是共享的。您可能想要这样:

class Node:

    def __init__(self,location):
        self.location = location
        self.nodes_neighbour = []
        self.nodes_neighbour_loc = []