Question

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<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

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]
Était-ce utile?

La solution

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.

Autres conseils

The objects are correct - and new objects - their repr however is wrong: int he __repr__ method of Tunnel you are printing the "x" and "y" variables, not the self.x and self.y attributes of the object.

The way your code is right now:

 def __repr__ (self):
      return "%s %s" % (str(x),str(y))

makes Python search for the global x and y variables - which happen to exist, and correspond to the values used to create the latest object.

Also - if you are using Python 2.x, make sure any classes you create inherit from object - otherwise you can find unexpected behavior ahead.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top