Newbie: List of instances?

Jeff Layton laytonjb at bellsouth.net
Fri Mar 29 15:57:18 EST 2002


Susan Williams wrote:

> >Hello,
> >
> >   I'm still learning Python and I'm playing around with some
> >code that creates a class. I've mastered that stage already.
> >However, what I want to do is create multiple instances of
> >the class and put them into a list.
> >   If the class is called Bob, then I want to do something like,
> >
> >
> >a = []
> >a[0] = Bob('input1')
> >
> >and so on. Everytime I try something like this I get the following
> >error message:
> >
> >a[0] = Bob( 'localhost' )
> >IndexError: list assignment index out of range
>
> Yeah, that is definitely a "no go".  You can't refer to a[0]
> because it doesn't exist--a is empty.
>
> >   I also tried it this way,
> >
> >a = []
> >a.append = Bob('localhost')
> >
> >and I get the error message:
> >
> >a[0] = Bob( 'localhost' )
> >IndexError: list assignment index out of range
>
> This is closer.  a itself is an object, and the way you deal
> with it, at least for some functions, is thru its methods.
> append is a method of the list object, so what you really want
> is:
>
> a.append(Bob('localhost'))

This works! If I create a list a that has five elements where
are just instances of Bob, can I "call" a method for a specific
element of the list? I take I can (Jeff sneaks off to experiment
while his wife is napping).

Thanks!

Jeff


>
>
> >
> >TIA,
> >
> >Jeff
>
> susan





More information about the Python-list mailing list