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

2024-04-26 12:16:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我定义了一个颜色类,如下所示。因为我需要存储多个颜色和它们各自的节点ID(具有该颜色),所以我创建了一个列表colors来存储它们。但是,每次更改节点颜色时,我都不想直接更新listcolors(另一个函数将决定是否更新),因此在调用decision func之前,我需要将colors的副本存储到*tmp\u colors*,如果结果为Yes,则用*tmp\u colors*更新colors。你知道吗

我设法复制了一个新列表*tmp\u colors*,但是*tmp\u colors[0]*仍然指向colors[0],导致两个列表都被更新。你知道吗

  1. 如何将colors[0]中的类对象复制到*tmp\u 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()

结果:

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

Tags: ofinself列表for颜色itemsrange
2条回答

您可以使用copy模块

import copy
tmp_colors = copy.deepcopy(colors)

您复制了列表,但没有复制内容,然后对其进行更改。您的Color实例也是可变的,并且tmp_colors[0]引用了与colors[0]相同的实例。当然,tmp_colors是一个副本,但是Color实例不是。你知道吗

使用^{}递归地创建对象的副本:

from copy import deepcopy

tmp_colors = deepcopy(colors)

相关问题 更多 >