James Franco
James Franco

Reputation: 4706

who actually calls __iter__ method

I am learning python and just started reading about iterators and iterables , I have read this post and this post both which try to explain this concept. However when reading this example. I have posted it below

class zrange:
    def __init__(self, n):
        self.n = n

    def __iter__(self):
        return zrange_iter(self.n)

class zrange_iter:
    def __init__(self, n):
        self.i = 0
        self.n = n

    def __iter__(self):
        # Iterators are iterables too.
        # Adding this functions to make them so.
        return self

    def next(self):
        if self.i < self.n:
            i = self.i
            self.i += 1
            return i
        else:
            raise StopIteration()

Now the above example is being used as such

>>> z = zrange(5)
>>> list(z)
[0, 1, 2, 3, 4]

My question is when or who calls the iter method ?

and my next question was what was the point of adding def __iter__(self) in class zrange_iter ?

Upvotes: 0

Views: 68

Answers (1)

nneonneo
nneonneo

Reputation: 179552

__iter__ is called by the iter builtin, and is also used to support iteration in the for ... in ... loop.

Upvotes: 2

Related Questions