如何在Python中复制数组中的类对象

时间:2013-07-16 11:39:44

标签: python python-2.7

我已经定义了一个 Color 类,如下所示。由于我需要存储多种颜色及其各自的节点ID(具有颜色),因此我制作了一个列表 colors 来存储它们。但是,每次更改节点颜色时,我都不想直接更新列表颜色(另一个函数将决定是否更新),因此我需要存储颜色的副本在调用决策函数之前到* tmp_colors *,如果结果为是,则用* tmp_colors *更新 colors

我设法制作新列表* tmp_colors *的副本,但* tmp_colors [0] *仍然指向 colors [0] ,导致两个列表的更新。

  1. 如何将 colors [0] 中的类对象副本复制到* tmp_colors [0] *?
  2. 如果我稍后更新 colors [0] ,最好的方法是什么?
  3. 有没有更好的设计而不是下面的例子(定义类和类对象列表)?

  4. class Color:
        __elems__ = "num", "nodelist",
    
        def __init__(self):
            self.num = 0
            self.num_bad_edge = 0
    
        def items(self):
            return [
                    (field_name, getattr(self, field_name)) 
                     for field_name in self.__elems__]
    
    def funcA():
    
        nodeCount = 2
        colors = []
        for i in range(0, nodeCount):
            colors.append(Color())
    
        colors[0].num = 2
        colors[0].nodelist = [10,20]
        colors[1].num = 3
        colors[1].nodelist = [23,33, 43]
    
        print "colors"
        for i in range(0, nodeCount):
            print colors[i].items()
    
        tmp_colors = list(colors)
        print "addr of colors:" 
        print id(colors)
        print "addr of tmp_colors:" 
        print id(tmp_colors)    
        print "addr of colors[0]:" 
        print id(colors[0])
        print "addr of tmp_colors[0]:" 
        print id(tmp_colors[0])
    
        tmp_colors[0].num = 2
        tmp_colors[0].nodelist = [10,21]
    
        print "\ntmp_colors"
        for i in range(0, nodeCount):
            print tmp_colors[i].items()
    
        print "\ncolors <<< have been changed"
        for i in range(0, nodeCount):
            print colors[i].items()
    

    结果:

    colors
    [('num', 2), ('nodelist', [10, 20])]
    [('num', 3), ('nodelist', [23, 33, 43])]
    addr of colors:
    32480840
    addr of tmp_colors:
    31921032
    addr of colors[0]:
    32582728
    addr of tmp_colors[0]:
    32582728                           <<<<<< --- expecting a new addr
    
    tmp_colors
    [('num', 2), ('nodelist', [10, 21])]
    [('num', 3), ('nodelist', [23, 33, 43])]
    
    colors <<< have been changed
    [('num', 2), ('nodelist', [10, 21])]   <<<<<< --- expecting no change [10, 20]
    [('num', 3), ('nodelist', [23, 33, 43])]
    

2 个答案:

答案 0 :(得分:5)

您复制了列表,但没有复制内容。您的Color个实例可变太多,而tmp_colors[0]指的是与colors[0]相同的实例。当然,tmp_colors是副本,但Color实例不是。

使用copy.deepcopy()递归创建对象的副本:

from copy import deepcopy

tmp_colors = deepcopy(colors)

答案 1 :(得分:1)

您可以使用copy模块

import copy
tmp_colors = copy.deepcopy(colors)
相关问题