Newbie: List of instances?
Bengt Richter
bokr at oz.net
Fri Mar 29 14:59:17 EST 2002
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.,
>>> 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'))
>>> 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.
Regards,
Bengt Richter
More information about the Python-list
mailing list