Franklin Harvey Franklin Harvey - 1 month ago 6
Python Question

Static List of Objects in Python

In python, everything is a "reference." In a simple program, I have a class:

class Watch(object):
def __init__(self, **kwargs):
self.variables = kwargs

def set_variable(self, k, v):
self.variables[k]=v

def get_variable(self, k):
return self.variables.get(k, None)

def print_info(self):
for k in self.variables:
print k + ": " + str(self.variables[k])


If I do:

list = []
tmp = Watch()
tmp.set_variable('name','frank')
list.append(tmp)
tmp.set_variable('name','doug')


then

list[0].get_variable('name')


is "doug"

How do I store temporary variables is lists or arrays while maintaining the array after appending?

Edit: Similar to How to clone or copy a list?, although I'm wondering more about the property of object storage in python. It seems like objects are treated as pointers, instead of just passing their contents. Can someone speak to that? For instance, in a language like C++ I could say

list[0]=tmp


and then i could alter tmp and list[0] would remain.

Answer

If I understand correctly, you want to put a copy of tmp in your list in such a way that if you subsequently modify tmp, then the copy of tmp in the list stays the same?

If so, then you probably want to use the copy module:

list = []
tmp = Watch()
tmp.set_variable('name','frank')
list.append(copy.deepcopy(tmp))
tmp.set_variable('name','doug')
list[0].get_variable('name') # returns 'frank'
Comments