Link to home
Start Free TrialLog in
Avatar of ol muser
ol muserFlag for United States of America

asked on

"instance has no attribute getitem" accessing python list item

Hi,

When the run the code below why am I not able to access my list that I have initialized and grown using extend? I get the error
AttributeError: polararray instance has no attribute '__getitem__'

class polararray:
   def __init__(self):
      self.oarray = []

   def add(self, a):
      self.oarray.extend([a])

   def palen(self):
      return len(self.oarray)

class orderarray:
   def __init__(self):
      self.raw_WQ = 0.0
      self.position = 0.0
      self.MCC = 0.0
      self.amplitude = 0.0

def main():
   pa = polararray()
   f = open("a.txt", "r")
   i = 0
   oa = None

   while True:
      line = f.readline().strip()
      if not line:
         break
      else:
         i += 1
         if '=' not in line:
            continue
         if 'raw_WQ' in line:
            if oa is not None:
               pa.add(oa)
            oa = None
            oa = orderarray()  
         (key, value) = line.split('=')
         if key in ('raw_WQ', 'position', 'MCC', 'amplitide'):
            if key == 'raw_WQ':
               oa.raw_WQ = value
            elif key == 'position':
               oa.position = value
            elif key == 'MCC':
               oa.MCC = value
            elif key == 'amplitude':
               oa.amplitude = value
            else:
               print 'ignoring key ', key
   #add the last one
   pa.add(oa)

   print i, ' lines read'
   print pa.palen()
   print pa[0].raw_WQ

if  __name__ =='__main__':main()

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of pepr
pepr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of ol muser

ASKER

@pepr, thanks for the coding guidelines.

I thought append and extend work differently. My choice was based on this: http://stackoverflow.com/questions/252703/append-vs-extend
Avatar of pepr
pepr

The append adds one element to the end of the list. The extend appends all elements from a container.

You have wrapped the a to the list constructor to create a one-element list and then you used the extend. So, the change only simplifies the same intention.