該程序從文件中讀取併爲文件的每一行上的數據創建一個Tunnel對象。該計劃的具體內容並不重要。輸出將清楚我遇到的問題。Python:在循環中創建對象的實例
每次我將一個新的隧道(名爲temp)追加到列表中時,所有舊的隧道(也稱爲先前for循環迭代中創建的temp)將更改爲新的隧道temp。如果出現混淆,請向下滾動並閱讀輸出結果。
class Tunnel: #I am using the data from the file to create tunnel objects
def __init__ (self,x,y,d):
self.x=x
self.y=y
self.d=d
def __lt__ (self,other):
return self.d<other.d
def __repr__ (self):
return "%s %s" % (str(x),str(y))
file = open("ant.in")
n=int(file.readline())
for i in range(0,n): #this loop is irrelevant
h,t=(int(s) for s in file.readline().split())
tList=[]
mst=[]
for j in range(0,t):
x,y,d=(int(s) for s in file.readline().split())
temp = Tunnel(x,y,d) #I create a new tunnel called "temp"
print(temp) #I print it. It prints as its x and y fields.
tList.append(temp) #I try and append this new tunnel to my list
print(tList) #the list prints all the tunnels, but all the tunnels are changed to the most recent one
而且程序輸出
1 2
[1 2]
2 3
[2 3, 2 3]
3 3
[3 3, 3 3, 3 3]
1 4
[1 4, 1 4, 1 4, 1 4]
名單應該打印
[1 2, 3 4, 3 3, 1 4]
是的,就是這樣!謝謝。 –
沒有必要使用str() –
這是真的,我會編輯它 - 只是保持原來的第一,但最好是正確的。 – antont