[Tutor] List of Objects?
Lloyd Kvam
pythontutor@venix.com
Thu, 31 Jan 2002 16:37:22 -0500
class Rooms:
def __init__(self, name, desc, exits):
self.name = name
self.desc = desc
self.exits = exits
make_rooms = (
( 'theKitchen', 'kitchen with dishwasher', 2),
( 'thePorch', 'porch needs new screens', 3),
( 'theAtic', 'attic with pull down steps',1),
)
avail_rooms = {}
for room in make_rooms:
# create room instances and store them in avail_rooms dictionary
# using the name of the room as the key
avail_rooms[room[0]] = Rooms( room[0], room[1], room[2])
This will create Rooms using the list (really tuples) of values in make_rooms
and store them in the dictionary avail_rooms using the name as the key.
If you'd rather, you could make avail_rooms a list, but then you would need to
access rooms by index number.
I hope this helps.
Britt Green wrote:
> Say I have a class called Rooms that looks something like this:
>
> class Rooms:
> def __init__(self, name, desc, exits):
> self.name = name
> self.desc = desc
> self.exits = exits
>
> Now, what I'm trying to do is to create a dozen or so rooms. I know I
> could do it like this:
>
> thePorch = Rooms(...)
> theKitchen = Rooms(...)
> theAttic = Rooms(...)
> ...etc...
>
> but this seems awfully tedious. It seems like creating an array of
> rooms would be much easier. I know that Python doesn't support arrays,
> and using a list would be the way to go. However, I'm not sure how to
> create a list of objects. Could anyone point me in the right direction?
>
> Britt
>
> =====
> "The ocean, she is strange and wondrous, filled with animals that disturb even a Frenchman."
>
> __________________________________________________
> Do You Yahoo!?
> Great stuff seeking new owners in Yahoo! Auctions!
> http://auctions.yahoo.com
>
> _______________________________________________
> Tutor maillist - Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor
>
>
--
Lloyd Kvam
Venix Corp.
1 Court Street, Suite 378
Lebanon, NH 03766-1358
voice:
603-443-6155
fax:
801-459-9582