The three-amp in Python has iterators, generators, adorners, and this article focuses on the next iterator
Iterators: Objects with __next__ and __iter__ methods
An iterative object: An object with a __iter__ method
1. Can iterate the object, can pass for...in ... Such statements iterate over a piece of data for the object we use to call it an iterative object (iterable), which can be judged by isinstance ()
In [1]: fromCollectionsImportIterablein [2]: isinstance ({},iterable) out[2]: Truein [3]: Isinstance ((), iterable) out[3]: Truein [4]: Isinstance ("", iterable) out[4]: Truein [4][ forIteminch {}: ...: Pass...: in [6]: forIteminch "": ...: Pass...: in [7]: forIteminch (): ...: Pass ...:
The nature of 2.for in
Li = [100, 200, 300, 400]#For num in Li:#print (num)#1. Get iterators by calling the __iter__ () of an iterative object#2. Iterate over the iterator call __next__,#if the stopiteration exception is not thrown, it means that the iteration is not over, and the acquired data element is placed in the variable#If an exception is thrown, indicating that the iteration is over, exit execution#3. Executing the loop body#4. Skip to 2nd Step executioniterator= li.__iter__() whileTrue:Try: Num= iterator.__next__() exceptstopiteration: Break Else: Print(num)
3. Custom Iterators
classmyiterable (object):def __init__(self): Self.container=[] # define a containerdefAdd (Self, item): Self.container.append (item)def __iter__(self):returnIterator (Self.container) # returns an iteratorclassIterator (object):def __init__(self, container): Self.container=Container self.i=0def __next__(self):ifSELF.I <Len (self.container): Count=self.i self.i+ = 1returnSelf.container[count]Else: Raisestopiterationdef __iter__(self):Passmi=myiterable () it= mi.__iter__() Mi.add (1) Mi.add (2) Mi.add (3) forIteminchmi:Print(item) fromCollectionsImportIteratorPrint(Isinstance (it, Iterator))
4. Merging iterators, the iterator that Python requires to define the iteration must implement __iter__ (self), and return the. Typically, an iterator that iterates over an object object is fixed, and the class and class
the need for distance between objects requires similarity, so you can often iterate over objects and Iterators are written together, which is the following.
classmyiterable (object):def __init__(self): Self.container=[] self.i=0defAdd (Self, item): Self.container.append (item)def __next__(self):ifSELF.I <Len (self.container): Count=self.i self.i+ = 1returnSelf.container[count]Else: Raisestopiterationdef __iter__(self):returnSELFMI=myiterable () Mi.add (1) Mi.add (2) Mi.add (3) forIteminchmi:Print(item)
Python three-amp iterator