[Tutor] why wont this code run?

Don Arnold Don Arnold" <darnold02@sprynet.com
Sun Jan 26 20:34:02 2003


----- Original Message -----
From: GREENDAY31087@aol.com
To: tutor@python.org
Sent: Sunday, January 26, 2003 7:05 PM
Subject: [Tutor] why wont this code run?


class Map:
         def __init__(self):
             self.__grid={} # Don't assume global startroom
         def addRoom(self, room, x, y):
             if self.__grid.has_key((x,y)):
                 raise KeyError, "Location occupied"
             self.__grid[(x, y)] = room
         def getRoom(self, x, y):
             return self.__grid[(x, y)]
         def getLocation(self, room):
             for coord, aRoom in self.__grid.items():
                 if room == aRoom:
                     return coord
             raise KeyError

    class Room:
         def __init__(self, map, x=0, y=0):
             self.__map = map
             map.addRoom(self, x, y)
         def dig(direction):

[---- my reply ----]

Well, the code won't make it past the parsing stage because Room.dig() is
broken: it has no body. Even if you give this method a body of 'pass',
you'll still have problems because its first parameter isn't 'self' (or some
equivalent). So, change it to:

def dig(self, direction):
    pass

and you should be ready to roll. If you run your code now, you shouldn't get
any errors. Of course, all you've done at this point is define 2 classes, so
you won't see anything going on until you add some driver logic that does
something with the classes:

if __name__ == '__main__':
    theMap = Map()
    room1 = Room(theMap)
    room2 = Room(theMap,1,1)
    room3 = Room(theMap,1,2)

    for somelocation in [room1, room2, room3]:
        print theMap.getLocation(somelocation)

>>>
(0, 0)
(1, 1)
(1, 2)

>>>

HTH,
Don