Изменение переменной в одном объекте обновляет ту же переменную другого объекта того же класса - PullRequest
0 голосов
/ 27 января 2020

Я написал класс Node и создал три объекта, когда я присваиваю значение переменной в 1-м объекте, обновляется та же переменная 2-го объекта, то же самое для третьего объекта. Вот код,

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 Ответ

1 голос
/ 27 января 2020

Ваши члены nodes_neighbour и nodes_neighbour_loc являются экземплярами класса и являются общими. Вы, вероятно, хотели это:

class Node:

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