[Tutor] How to use __iter__

Jia-Yu Aw jiayuaw at yahoo.com.sg
Tue Aug 9 03:48:20 CEST 2011

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:
                y = setCopy[0]
            except StopIteration:
        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()
    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)

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20110809/9af8b7d1/attachment.html>

More information about the Tutor mailing list