[Tutor] 'str' object has no attribute 'description'

Wayne Werner waynejwerner at gmail.com
Mon Dec 19 00:41:29 CET 2011


On Sun, Dec 18, 2011 at 4:49 PM, Russell Shackleton <rshack at xtra.co.nz>wrote:

> I am learning Python classes by writing an adventure game. I have
> extracted just the relevant code. The player can look, go, drop, take,
> inventory but not examine.
>
> Python produces the error message in the Player class, examine function,
> in the first print statement.
>
> I have added the traceback following a suggestion from Wayne Werner.
>

That's much more useful. As a slight aside, it probably would have been
better to just reply-all to the original thread with the traceback.


>
> Traceback (most recent call last):
>  File "adv03.py", line 205, in <module>
>    main()
>  File "adv03.py", line 202, in main
>    game.play(adventurer)
>  File "adv03.py", line 147, in play
>    character.examine(cmdlist[1])
>  File "adv03.py", line 86, in examine
>    print "Item Description: " + item.description + ".\n"
> AttributeError: 'str' object has no attribute 'description'
> [Note: actual line numbers appended in comments in this listing]
>
>
This is *much* more helpful - I don't even need to see your code to tell
you what went wrong. I don't know if you've worked with other programming
languages with nearly useless stack traces, but in Python you'll find that
they're (usually) very high quality. In this case it tells you a few
things. First, it tells you where it happened with this line:

>  File "adv03.py", line 86, in examine

It happened in the file adv03.py, on line 86, in a function (or method)
called "examine".

The next two lines tell you what blew up, and why it did:

   print "Item Description: " + item.description + ".\n"
> AttributeError: 'str' object has no attribute 'description'


'str' object has no attribute 'description'. Well if you look on the line
before that the only description attribute you try to look up is
item.description. So if 'str' doesn't have that attribute then item must be
a string.

With that in mind, let's take a look at that function:

   def examine(self, item):
>        """Prints description of item."""
>        if item in self.items:
>            # Error: 'str' object has no attribute 'description'
>            print "Item Description: " + item.description + ".\n" # line 86
>        else:
>            print "You are not holding the " + item + " to examine!\n"


This looks pretty straightforward. You pass something in as item, and check
to see if it's contained in your list of items. If it is, then you print
out the description, otherwise you print out whatever you passed in.

And so if we rewind back to where you call the function:

  character.examine(cmdlist[1]) # line 147


What is cmdlist? A list of strings. What is contained in cmdlist[1]?

If you still have issues fixing this, please let us know.

HTH,
Wayne

How do I fix this code, please?
>
> class Player(object):
>    """The player in the game."""
>    def __init__(self, name, currentRoom=None):
>        self.name = name
>        self.currentRoom = currentRoom
>        self.items = [] # items taken by Player
>
>    def look(self):
>        """Prints the room description, exits and items in the current
> room."""
>        print self.currentRoom
>
>    def go(self, direction):
>        """Go to another room through an exit."""
>
>    def drop(self, item):
>        """Drop an item you are carrying in the current room."""
>
>    def take(self, item):
>        """Take (pick up) an item from the current room."""
>        if item == self.currentRoom.item:
>            self.items.append(item)
>            print self.currentRoom.item + " added to player's inventory.\n"
>            # remove item from currentRoom
>            self.currentRoom.item = ''
>        else:
>            print "There is no " + item + " here to take!\n"
>
>    def inventory(self):
>        """Prints list of items the player is carrying."""
>
>    def examine(self, item):
>        """Prints description of item."""
>        if item in self.items:
>            # Error: 'str' object has no attribute 'description'
>            print "Item Description: " + item.description + ".\n" # line 86
>        else:
>            print "You are not holding the " + item + " to examine!\n"
>
> class Item(object):
>    """A useful item in the game."""
>    def __init__(self, name, description, location):
>        self.name = name
>        self.description = description
>        self.location = location
>
>    def __str__(self):
>        """Description of item."""
>        return self.description
>
> class Game(object):
>    """The adventure game."""
>    def __init__(self, name, player):
>        self.name = name
>        self.player = player
>        print "Welcome to " + self.name + "\n"
>        print player.currentRoom
>
>    def play(self, character):
>        """Command loop for game."""
>        while True: # loop forever
>            commands = raw_input("-> ").lower()
>            if not commands:
>                print "Huh?"
>            else:
>                try:
>                    cmdlist = commands.split()  # separate commands
>                    action = cmdlist[0]
>                    if action == "quit":
>                        print "See you later!"
>                        break
>                    elif action == "look":
>                    elif action == "go":
>                    elif action == "take":
>                    elif action == "drop":
>                    elif action == "examine":
>                        if len(cmdlist) != 2:
>                            print "An examine command must be followed by
> an item name."
>                            continue
>                        else:
>                            character.examine(cmdlist[1]) # line 147
>                    elif action == "inventory":
>                except AttributeError, msg:
>                    print "Error - undefined method: " + str(msg)
>
> def main():
>    # Room descriptions
>    room5 = Room(name="hallway", description="You are in a dark hallway.",
> item="diary")
>
>    # Item descriptions
>    diary = Item(name="diary", description="grey-covered Croxley diary",
> location=room5)
>
>    game.play(adventurer)       # line 202
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> http://mail.python.org/mailman/listinfo/tutor
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20111218/3ceb4afa/attachment.html>


More information about the Tutor mailing list