如下面所定義的顏色類。因爲我需要存儲多種顏色和它們各自的節點ID(其具有的顏色),我做了一個列表顏色來存儲它們。然而,每一個節點的顏色改變時,我不想更新列表顏色直接(另一個功能將決定是否更新或沒有),所以我需要存儲的顏色到副本* tmp_colors *調用之前決定函數,並且如果結果爲是,則更新顏色帶* tmp_colors *。我已經如何複製類對象中的陣列在Python
我設法創建新列表* tmp_colors *的一個副本,但* tmp_colors [0] *仍然指向顏色[0],導致這兩個列表的更新。
- 我怎樣才能使類對象的副本顏色[0]爲* tmp_colors [0] *?
- 如果我要更新顏色[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])]