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

Alan Gauld alan.gauld at btinternet.com
Mon Dec 19 01:41:35 CET 2011


On 18/12/11 22:06, Russell Shackleton wrote:
> I have extracted just the relevant code.

Its possible you extracted too much but....

> class Player(object):
>      """The player in the game."""
>      def __init__(self, name, currentRoom=None):
>      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 = ''

Here at least you are making item a string rather than an Item()

>      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"

And here you access the item.description which doesn';t exist for strings.
But you could get rounfd that by converting item to a str(). Then if it 
is an Item instance your __str__ method gets called - thats why you 
defined it right? - and if its already a string the same string gets 
returned...

>              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):
>      def play(self, character):
>
> def main():
>      # Room descriptions
>      room5 = Room(name="hallway", description="You are in a dark hallway.", item="diary")
>

Notice that  the item is just a strinng, not the diary object. Which 
doesn't actually exist yet anyhow!

>      # Item descriptions
>      diary = Item(name="diary", description="grey-covered Croxley diary", location=room5)

This appears to be the only place you ever instantiate an Item? But this 
is not what you assigned to room5...

So you are not assigning Items to the rooms. Unless its in the code you 
deleted?

HTH,

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/



More information about the Tutor mailing list