Iterators
An object that can directly act on a for loop is called an iterative object (iterable).
An object that can be called by the next () function and continually returns the next value is called an iterator (Iterator).
All iterable can be converted to iterator via the built-in function iter ().
names = ITER (['Sun','IBM','Sunny'])Print(names)Print(names.__next__())Print(names.__next__())Print(names.__next__())Print(names.__next__())#first output Print iterator object#the next method for the No. 234 time gets the value of the iteration object each time, taking a value down until the end of the#fifth time output print (names.__next__ ())#Stopiteration, this exception occurs because the object inside the iterator has been exhausted
View Code
Generator
In Python, this side loop is calculated as a mechanism, called the generator: generator
deffib (max): N,a,b= 0,0,1 whileN <Max:#print (b) yieldb A, a= b,a+B N+ = 1return ' Done'Data= FIB (10)Print(data)Print(Data.__next__())Print(Data.__next__())Print("do something else.")Print(Data.__next__())Print(Data.__next__())Print(Data.__next__())Print(Data.__next__())Print(Data.__next__())
View Code
Asynchronous application of the generator
Import TimedefConsumer (name):#Defining consumer functions Print("%s ready to eat buns!"% name)#Print Consumer name whileTrue:baozi=yield #Contemporary code run to this point, an iterator object is returned, and when the object is called for the second time, it receives the value and assigns the value to Baozi Print("Bun [%s] came, eaten by [%s]!"% (Baozi, name))#prints the currently used iterator object, and the value receiveddefProducer (*name):#Define a producer function, and use dynamic parameters ifLen (name) = = 3:#Three consumer function methods are called when three parameters are passedc =consumer (name[0]) C2= Consumer (name[1]) C3= Consumer (name[2]) c.__next__()#get an iterator inner element through a function built-in methodC2.__next__() C3.__next__() Print("Lao Tzu began to prepare steamed buns!") forIinchRange (1, 11): Time.sleep (1) Print("made a%s bun!"%Len (name)) c.send (i)#passing values to the generator via the Send property of the iterator methodc2.send (i) c3.send (i) Producer ("Alex",'Zengchunyun','Peiqi')#Create a Producer object and pass in three consumer names
View Code
Decorative Device
def Wrapper (func): def Inner (name): func (name) return inner@wrapperdef Index (name): Print ('welcome%s' % name) index ('Alex')
View Code
Python Iterator builder Decorator