Hi all
I've been learning Classes and have read the documentation on __iter__ but
still don't understand how it works. I have two pieces of code: the first is
def __iter__, the second is using __iter__. Instead of being an iterator, I'm
just using this is a function, which I think is incorrect. Can somebody explain
__iter__ and, if it's related, next()?
This is the first. But unlike what it says in the triple quotes, I return a
whole list instead of a single shape:
def __iter__(self):
"""
Return an iterator that allows you to iterate over the set of
shapes, one shape at a time
"""
import copy
setCopy = copy.copy(self.set)
shapeList = []
while len(setCopy) > 0:
try:
y = setCopy[0]
shapeList.append(y)
setCopy.remove(y)
except StopIteration:
break
return shapeList
The second, how I've used __iter__:
def findLargest(shapes):
"""
Returns a tuple containing the elements of ShapeSet with the
largest area.
shapes: ShapeSet
"""
## TO DO
areaList = []
areaDict = {}
largestDict = {}
shapeList = shapes.__iter__()
for s in shapeList:
areaDict[s] = s.area()
areaList.append(s.area())
largestArea = max(areaList)
areaList = [] #re-initialize areaList, cleaning it
import copy
dictCopy = copy.copy(areaDict)
for a in areaDict:
if areaDict[a] != largestArea:
del dictCopy[a]
return tuple(dictCopy)
Thanks
_______________________________________________
Tutor maillist - Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor