ImInEvItAblE
ImInEvItAblE

Reputation: 13

Changing a variable in one object is updating same variable of same class's another object

I wrote a Node class and created three objects, when I'm assigning a value of a variable in the 1st object, the same variable of 2nd object is getting updated, same for the third object. Here's the code,

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)

and it's printing, [[50, 10], [90, 10]]

What's the problem?? Thanks in advance :)

Upvotes: 0

Views: 36

Answers (1)

quamrana
quamrana

Reputation: 39354

Your members nodes_neighbour and nodes_neighbour_loc are instances of the class and are shared. You probably wanted this:

class Node:

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

Upvotes: 1

Related Questions