Franklin Harvey Franklin Harvey - 11 months ago 60
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):

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()



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


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

Answer Source

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()
list[0].get_variable('name') # returns 'frank'