python - How to avoid objects of a same class having same id? -


i trying work particular object in many instances of class. whenever adding value object, turns out adding value objects of other instances of class.

this post suggested had same id objects gc freeing , loading objects on same memory.

node class has object neighbors set neighbors = []

grid = [[node() x in range(col)] 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 possible workaround temp2 have empty list?

i guess doing similar in node.__init__():

class node(object):     def __init__(self, neighbors=[]):         self.neighbors = neighbors  n1 = node() n2 = node()  >>> n1.neighbors n2.neighbors true >>> n1.neighbors.append('hi') >>> n2.neighbors ['hi'] 

that's because same list. can instead:

class node(object):     def __init__(self, neighbors=none):         if neighbors not none:             self.neighbors = neighbors         else:             self.neighbors = []  n1 = node() n2 = node()  >>> n1.neighbors n2.neighbors false >>> n1.neighbors.append('hi') >>> n2.neighbors [] 

problem solved?


Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -