[Tutor] __iter__

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Tue Jan 17 19:26:51 CET 2006


> One small correction: Pointer should have an __iter__() method that
> returns self; this is part of the iterator protocol. See PEP 234
> http://www.python.org/peps/pep-0234.html

Hi Kent,

Ah, thank you!  Ok, the corrected code is:

#################################################
class MyListOfNumbers:
    def __init__(self, data):
        self.data = data

    def __iter__(self):
        return Pointer(self)

class Pointer:
    def __init__(self, numbers):
        self.numbers = numbers
        self.offset = 0

    def __iter__(self):
        return self

    def next(self):
        if self.offset == len(self.numbers.data):
            raise StopIteration
        element = self.numbers.data[self.offset]
        self.offset = self.offset + 1
        return element
#################################################




More information about the Tutor mailing list