[Tutor] Problem with creating class instance

Kent Johnson kent37 at tds.net
Wed Jul 9 23:46:17 CEST 2008


On Wed, Jul 9, 2008 at 5:02 PM, Mike Meisner <mikem at blazenetme.net> wrote:

> In creating a Player instance,  that instance can create the Stats class,
> but when creating the first instance within the Stats class of a Details
> class, it fails with the following traceback:
>
> Traceback (most recent call last):

>   File "C:\Documents and Settings\Mike and Patsy\Desktop\pk\pkutilities.py",
> line 29, in __init__
>     self.gamephase[0] = Details('full')
> IndexError: list assignment index out of range
>
>
> The appropriate code segments defining the classes and the calling function
> follow:

> class Stats():
>
>     def __init__(self, type, name):
>         self.name = name
>         self.gametype = type
>         self.totalgames = 0
>         self.totalgamestofinish = 0
>         self.totalfinish = 0
>         self.gamephase[0] = Details('full')    # this is the line which
> fails

You don't show how self.gamephase is initialized. I assume you say
something like
  self.gamephase = []
because if you didn't initialize it at all you would get a NameError
rather than IndexError.

You can't assign to a list element that doesn't exist, it will raise
IndexError; e.g.
In [19]: phase = []

In [20]: phase[0] = 'test'
---------------------------------------------------------------------------
<type 'exceptions.IndexError'>            Traceback (most recent call last)

/Users/kent/<ipython console> in <module>()

<type 'exceptions.IndexError'>: list assignment index out of range

You can append to the list:
In [21]: phase.append('test')

Now it has a zeroth element:
In [22]: phase[0]
Out[22]: 'test'

but a simpler solution might be just to create the list with the
elements you want:

self.gamephase = [ Details('full') , Details('mid'), Details('end') ]

>     for i in range(len(playernames)):
>         name = playernames[i]

Write this as
  for name in playernames:

> I don't see how the "list assignment index" can be out of range, so I assume
> there's an earlier error that I can't find or a syntax error that I'm
> overlooking.

No, if it says the index is out of range, it probably is. This might
be a symptom of an earlier error but you should believe the error
message.

A syntax error will prevent the program from running at all.

Kent


More information about the Tutor mailing list