Skip to content Skip to sidebar Skip to footer

Python: Create Instance Of An Object In A Loop

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 th

Solution 1:

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.

Solution 2:

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.

Post a Comment for "Python: Create Instance Of An Object In A Loop"