[英]Python list assignation
我有這個代碼
class coordenates:
x = 0
y = 0
coor = coordenates()
coor.x=0
coor.y=0
list = []
list.append(coor)
list.append(coor)
現在,問題在於我更新時
list[0].x=100
它也以某種方式修改了list[1].x
!
print str(list[0].x)
>> 100
print str(list[1].x)
>> 100
由於我沒有更新,因此必須保持為0
。 append()
是否在位置0和1的內存中創建指向同一位置的相同對象? 為什么創建2個不同的對象解決了這個問題?
在當前代碼中, x
和y
是類級屬性。 我懷疑你希望它們是實例級屬性。 如果是這樣,請在__init__()
設置它們:
class Coordinates:
def __init__(self):
self.x = 0
self.y = 0
更重要的是,如果你將同一個coor
追加到列表中兩次,那么coor
任何變異都將反映在“both”坐標中(因為列表只是在列表的兩個位置都持有對相同底層坐標的引用)。 也許你想要這樣的東西,你在哪里創建兩個獨立的坐標實例?
list = []
list.append(Coordinates())
list.append(Coordinates())
您可以使用以下代碼查看問題的說明:
c = Coordinates()
cs = []
cs.append(c)
cs.append(c)
for c in cs:
print id(c) # Both elements of the list refer to the same object.
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.