我定义了一个 Color 类,如下所示。由于我需要存储多种颜色及其各自的节点 ID(具有颜色),因此我制作了一个 colors 列表来存储它们。但是,每次更改节点颜色时,我不想直接更新列表colors(另一个函数将决定是否更新),所以我需要存储一份colors 在调用决策函数之前更改为 *tmp_colors*,如果结果为 Yes,则将 colors 更新为 *tmp_colors*。
我设法制作了新列表 *tmp_colors* 的副本,但 *tmp_colors[0]* 仍指向 colors[0] ,导致两个列表的更新。
- 如何将 colors[0] 中的类对象复制到 *tmp_colors[0]*?
- 如果我以后要更新colors[0],最好的方法是什么?
- 有没有更好的设计来代替下面的例子(定义类,和类对象列表)?
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])]
请您参考如下方法:
您复制了列表,但没有复制内容,然后您更改了它。您的 Color 实例也是可变的,并且 tmp_colors[0] 指的是与 colors[0] 相同的实例做。当然,tmp_colors 是一个副本,但 Color 实例不是。
使用copy.deepcopy()以递归方式创建对象的副本:
from copy import deepcopy
tmp_colors = deepcopy(colors)
