Detailed explanation of python iterator

Keywords: Python

Iterator notes:

What is an iterative object:

  1. What to do: to traverse for...in.
  2. Known data types: list, dict, tuple, str, set, generator.
  3. Conditions to be met: a method of "iterator" needs to be implemented, and the method returns an iterator object.

What is an iterator:

  1. What to do: to return data, the iterator's next function or next function will be called every time the loop, through which data can be obtained
  2. Conditions to be met:
    • In Python 2: there are two methods to implement, namely, the "iter" method and the "next" method.
    • In Python 3: there are two methods to implement, namely, the "iter" method and the "next" method.

iter function:

Iterator used to get an iteratable object.

Write a structure that can be traversed with for...in... By yourself:

class MyRangeIterator(object):
    def __init__(self,start,end):
        self.index = start
        self.end = end

    def __iter__(self):
        return self

    def __next__(self):
        if self.index < self.end:
            temp = self.index
            self.index += 1
            return temp
        else:
            raise StopIteration()

class MyRange(object):
    """
    MyRange Is an iterative object
    """
    def __init__(self,start,end):
        self.start = start
        self.end = end

    def __iter__(self):
        # This method returns an iterator object
        return MyRangeIterator(self.start,self.end)

ret = MyRange(1,10)
for x in ret:
    print(x)

If two identities of iterator and iteratable object are placed in the same object, then the iteratable object can only be traversed once:

class MyRange(object):
    """
    MyRange Is an iterative object
    """
    def __init__(self,start,end):
        self.start = start
        self.end = end
        self.index = start

    def __iter__(self):
        # This method returns an iterator object
        return self

    def __next__(self):
        if self.index < self.end:
            temp = self.index
            self.index += 1
            return temp
        else:
            raise StopIteration()

my_range = MyRange(1,10)
for x in my_range:
    print(x)

print('='*10)
for y in my_range:
    print(y)

Posted by skissiks on Mon, 11 May 2020 08:44:50 -0700