我定义了一个颜色类,如下所示。因为我需要存储多个颜色和它们各自的节点ID(具有该颜色),所以我创建了一个列表colors来存储它们。但是,每次更改节点颜色时,我都不想直接更新listcolors(另一个函数将决定是否更新),因此在调用decision func之前,我需要将colors的副本存储到*tmp\u colors*,如果结果为Yes,则用*tmp\u colors*更新colors。你知道吗
我设法复制了一个新列表*tmp\u colors*,但是*tmp\u 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])]
您可以使用
copy
模块您复制了列表,但没有复制内容,然后对其进行更改。您的
Color
实例也是可变的,并且tmp_colors[0]
引用了与colors[0]
相同的实例。当然,tmp_colors
是一个副本,但是Color
实例不是。你知道吗使用^{} 递归地创建对象的副本:
相关问题 更多 >
编程相关推荐