0

I am trying to work with a particular object in many instances of a class. However whenever I am adding a value to that object, turns out it is adding the value to objects of all other instances of the class.

This SO post suggested that I had same id for my objects as the GC freeing up and loading objects on the same memory.

Node class has an object neighbors set as neighbors = []

grid = [[node() for x in range(col)] for y in range(row)]

temp1 = grid[0][0].neighbors
temp2 = grid[4][0].neighbors

print id(temp1)
print id(temp2)

temp1.append("sth")

print temp1
print temp2

Output:

38412376
38412376
['sth']
['sth']

What would be a possible workaround for temp2 to have an empty list?

Community
  • 1
  • 1
Roy
  • 59
  • 6

1 Answers1

1

I guess that you are doing something similar to this in Node.__init__():

class Node(object):
    def __init__(self, neighbors=[]):
        self.neighbors = neighbors

n1 = Node()
n2 = Node()

>>> n1.neighbors is n2.neighbors
True
>>> n1.neighbors.append('hi')
>>> n2.neighbors
['hi']

That's because they are the same list. You can do this instead:

class Node(object):
    def __init__(self, neighbors=None):
        if neighbors is not None:
            self.neighbors = neighbors
        else:
            self.neighbors = []

n1 = Node()
n2 = Node()

>>> n1.neighbors is n2.neighbors
False
>>> n1.neighbors.append('hi')
>>> n2.neighbors
[]

Problem solved?

mhawke
  • 84,695
  • 9
  • 117
  • 138
  • I was doing exactly that. I had declared a list `neighbors = []`. However in my *Node* class I also have declared `pos = ""` and `visited = True`. But as I change them in one instance in the same way, that doesn't seem to affect other objects of different instances like the neighbor list did. Why is that? – Roy Jan 17 '16 at 00:18
  • 1
    That's because strings and booleans (ints) are _immutable_. You can't change their values. When you try to alter them you are actually _rebinding_ a new instance to an attribute or variable. Lists are mutable containers; their items can be altered without altering the container. In the case where a list is used as a default argument to a function, there is only one list which is created when the function is defined. It's better explained [here](http://docs.python-guide.org/en/latest/writing/gotchas/#mutable-default-arguments). – mhawke Jan 17 '16 at 06:07