[Tutor] AttributeError

Paul Sidorsky paulsid@shaw.ca
Sun, 24 Feb 2002 22:11:25 -0700

Britt Green wrote:

> Can anyone tell me why I get this error on the following code, and what
> a good solution for it would be?

>             playerLoc = playerLoc.exits.get(command[0])

This is the offending line.  playerLoc is supposed to be a Room object,
but here you're assigning it a string.

The "quick fix" solution is to just put eval() around that as follows:
             playerLoc = eval(playerLoc.exits.get(command[0]))

This works (I tested it) except that you can't use names with spaces or
operators in there.  (Your "dining room" example will fail if not
renamed.)  However, what the above actually does is it "runs" the name
of the room which will return the actual variable name, and it's a nasty
idea to muck about in your program's namespace when you don't have to.

A better idea would be to put all your Room objects in another
dictionary, with the key being the room name.  Kind of like this:

rooms = {}
rooms["foyer"] = Room(...)

Then playerLoc can store a string and use it to key that dictionary to
find the right room.  Since you already seem to have a handle on
dictionaries it shouldn't be too hard to make the modifications.

BTW, on a semi-related note, I just can't help giving a plug to the
Inform language which is designed specifically for text adventures:


Inform actually has a very Pythonic feel to its syntax (IMO), although
it is structured quite differently and is not a general purpose

Obviously this won't help you if you're writing a text adventure for the
purpose of learning Python, but I just wanted to mention it in case
anybody's interested because I think it's a neat language.

Paul Sidorsky                                          Calgary, Canada
paulsid@shaw.ca                        http://members.shaw.ca/paulsid/