Static List of Objects in Python

时间:2016-10-20 19:01:04

标签: python list pointers

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.

1 个答案:

答案 0 :(得分:3)

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'