[Tutor] Picking up Item()s
Michael P. Reilly
arcege@speakeasy.net
Sun, 17 Feb 2002 20:51:29 -0500
On Sun, Feb 17, 2002 at 04:31:00PM -0800, Britt Green wrote:
> Unfortunately I'm stuck on this point: When a player enters a room it
> doesn't say "This room contains a key." Instead it says "This room
> contains [<__main__.Item instance at 0x00AC5320>]". How can I make it
> so that it displays the name of the Item. Furthermore, I'd want the
> player to be able to type "get key" to pick up the key, not
> "__main__.Item instance at 0x00AC5320". How could I do this?
If you are going to "print" objects, then you'll want to add the
__str__ method to the class. The string returned from that method
is used instead of what you saw before.
> Britt
>
> import sys
> import string
>
> class Room:
> def __init__(self, name):
> self.name = name
> self.items = []
>
> def createExits(self, exits):
> self.exits = exits
>
> def itemsInRooms(self, item):
> self.items.append(item)
>
> class Item:
> def __init__(self, name):
> self.name = name
> self.inPosses = 0
# what is the printed name
def __str__(self):
# 'a key' or 'a door'
return 'a %s' % self.name
# compare the name to another object, like a string
def __cmp__(self, other):
return cmp(self.name, other)
>>> keyitem = Item('key')
>>> print 'you have', keyitem
you have a key
>>> items = [ keyitem, Item('door') ]
>>> item2find = 'key' # a string
>>> item2find in items
1
>>> try:
... pos = items.index(item2find)
... except IndexError:
... print item2find, 'not found'
... else:
... print 'I found', repr(items[pos])
...
I found <__main__.Item instance at 0x815202c>
>>>
The __cmp__ method can help you find the right object you want from
the string.
Good luck,
-Arcege