概述
This program reads from a file and creates a Tunnel object for the data on each line of the file. The specifics of the program don't really matter. The output will make it clear the problem I am having.
Every time I append a new Tunnel (named temp) to the list, all the old Tunnels (also named temp which were created in previous iterations of the for loop) are changed to the new Tunnel temp. If that is confusing, please scroll down and read the output.
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
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
And the program outputs
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]
The list should print
[1 2, 3 4, 3 3, 1 4]
解决方案
It's your __repr__ -- use self.x & self.y there:
def __repr__ (self):
return "%s %s" % (self.x, self.y)
So your code is actually working but the print of the objects is incorrect. Instead of the instance attributes it is printing x & y from global scope.
最后
以上就是深情御姐为你收集整理的python循环创建对象_Python:在循环中创建对象的实例的全部内容,希望文章能够帮你解决python循环创建对象_Python:在循环中创建对象的实例所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复