Python: instantiate an object in a loop

This program reads from a file and creates a Tunnel object for the data in each line of the file. The specifics of the program do not really matter. The result will clear the problem I am having.

Every time I add a new Tunnel (named temp) to the list, all old tunnels (also called temp, which were created in previous iterations of the for loop) are replaced with the new Tunnel temp. If this is confusing, 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]

      

List should print

[1 2, 3 4, 3 3, 1 4]

      

+1


source to share


2 answers


This is your __repr__

- use self.x

and self.y

there:

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

      



So your code does work, but the printing of the objects is wrong. Instead of the instance attributes, it prints to x

and y

from the global scope.

+3


source


Objects are true - and new facilities - they are repr

, however, wrong: int he __repr__

method Tunnel you print variable "x" and "y", and not self.x

, and self.y

object attributes.

What your code looks like right now:

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

      



allows Python to look for global variables x and y that exist and match the values โ€‹โ€‹used to create the last object.

Also - if you are using Python 2.x make sure all classes you create inherit from object

- otherwise you might find unexpected behavior ahead.

0


source







All Articles