ol muser
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
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()
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
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.
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.
ASKER
I thought append and extend work differently. My choice was based on this: http://stackoverflow.com/questions/252703/append-vs-extend