Newbie: List of instances?

Bengt Richter bokr at oz.net
Fri Mar 29 22:42:00 EST 2002


On 29 Mar 2002 19:59:17 GMT, bokr at oz.net (Bengt Richter) wrote:

>On Fri, 29 Mar 2002 14:29:31 -0500, Jeff Layton <laytonjb at bellsouth.net> 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
>>
>Because there is no a[0] yet if a is []
>>
>>   I also tried it this way,
>>
>>
>>a = []
>>a.append = Bob('localhost')
>>
>That much should work. Can you copy and paste an actual interactive snippet? E.g.,
>
Oops, misread that, sorry. That really should have gotten you the error (on 2.2 at least):

    message AttributeError: 'list' object attribute 'append' is read-only

which would have been a good clue.

The following is verbatim from my screen however (see how much more reliable that is? ;-)

> >>> class Bob:
> ...     def __init__(self,v):
> ...         self.v = v
> ...     def show(self):
> ...         print 'This is a Bob instance with v = %s' % self.v
> ...
> >>> a = []
> >>> a.append(Bob('localhost'))
      ^^^^^^^^^^^^^^^^^^^^^^^^^^-- what I thought I read above, which is why I "reproduced" it.
> >>> a
> [<__main__.Bob instance at 0x007CF4A0>]
> >>> a[0]
> <__main__.Bob instance at 0x007CF4A0>
> >>> a[0].show()
> This is a Bob instance with v = localhost
>
>>
>>and I get the error message:
>>
>>
>>a[0] = Bob( 'localhost' )
>>IndexError: list assignment index out of range
>>
>a must have still been [], but who can tell from what you posted?
>
>>   Can anyone shed some light into how I do this? Or is
>>there a better way?
>>
>Post a log of minimal failing code sufficient for anyone
>to duplicate your problem.
>
Always best.

Regards,
Bengt Richter



More information about the Python-list mailing list