Newbie: List of instances?

Susan Williams susan at mars.provis.com
Fri Mar 29 15:09:17 EST 2002


>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'))

>
>TIA,
>
>Jeff

susan





More information about the Python-list mailing list