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

twf*_*wfx 1 python python-2.7

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

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

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

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()
Run Code Online (Sandbox Code Playgroud)

结果:

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])]
Run Code Online (Sandbox Code Playgroud)

Mar*_*ers 5

您复制了列表,但没有复制您随后更改的内容.你的Color情况是可变,并tmp_colors[0]指作为同一实例colors[0]做.当然,tmp_colors是副本,但Color实例不是.

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

from copy import deepcopy

tmp_colors = deepcopy(colors)
Run Code Online (Sandbox Code Playgroud)