【发布时间】:2014-06-28 12:25:07
【问题描述】:
此程序从文件中读取数据并为文件每一行的数据创建一个 Tunnel 对象。该计划的细节并不重要。输出将清楚地说明我遇到的问题。
每次我将新隧道(名为 temp)添加到列表时,所有旧隧道(也称为 temp,在 for 循环的先前迭代中创建)都会更改为新隧道 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]
【问题讨论】:
标签: python list loops object naming