python can iterate over objects--iterable
Python often uses a for to iterate over an object, at which point the object being traversed is an iterative object, such as the common list, tuple, dict, set, and Str. If an exact definition is given, it is an iterative object as long as it defines a iter method that can return an iterator, or defines a GetItem method that can support the subscript index.
Python iterator object--iterator
The iterator is implemented by next (), and every time he calls, he returns the next element, returning a stopiteration exception when there is no next element, so the actual definition of the method is an iterator. An iterator must be an iterative object, which in turn is not necessarily true. The ITER () function can turn list, dict, str and other iterable into iterator
The following is illustrated by creating an iterator object:
Creates a reverse object that flips the objects in the sequence.
Class Reverse (object):
def __init__ (self, data):
self.data = data
Self.index = Len (data)
def __iter__ ( Self): return
self
def __next__ (self):
if Self.index = 0:
raise stopiteration
self.index-= 1< C13/>return Self.data[self.index]
rev = Reverse ([1,2,3,4,5]) for
x in Rev:
print (x)
Get the result:
5
4
3
2
1
In the For Loop, the ITER () method is invoked first, an iterator object is called, and then the next () method of the Iterator object is invoked, returning a value at a time.
——————————————————————————
three ways to create iterators:
1. Define a container and add the iter() and next() methods (the next () method in Python 2);iter() returns the Iterator object itself,next() Returns the element each time the next () or iteration is invoked;
2, through ITER () to convert the iterative object to the iterator;
3, Generator. The generator quickly generates iterators through yield statements, omitting the complex iter() and next() methods.