[Tutor] subscript problem

Jeff Shannon jeff@ccvcorp.com
Tue Jun 3 14:48:01 2003


Jimmy verma wrote:

> Actually it is not possible for me to write the whole code as it is 
> too lengthy. I have formulated the section in which i am getting the 
> problem so i have written the code for the problem i am having. It 
> takes the form like this and give the error written after the code:
>
> class AB:
>    def __init__(self):
>        self.n_p = None
>        self.po = Vec()      # in c struct this is Vec* po
>        self.con = []        # in c struct this is short* con


Here you've created AB.po as a *single* instance of class Vec.

> def XYZ(out):
>    n = 0
>    out.con.append(5)
>    last = out.con[n]     # say n to some int value, last is also integer
>    v_start = out.po[last] 


Here, you're trying to access out.po as if it's a *list* of Vec 
instances.   This is why you're getting the error -- it's essentially 
telling you that out.po is not a list.  (You can define custom list-like 
objects by writing a few special methods, such as __getitem__(), which 
is why the exception is worded the way it is...)

In C, it's possible to conflate pointers and arrays, but in Python, 
lists are a very distinct thing.  If you want AB.po to refer to a list 
of vector items, you need to explicitly create a list:

class AB:
   def __init__(self):
       [...]
       self.po = [Vec()]      # in c struct this is Vec* po

This gives me a list containing a single item, and I can then append() 
further items to that list if needed.

Hope that this makes things a bit clearer...

Jeff Shannon
Technician/Programmer
Credit International