#Generator and co-process#A generator is a special iterator that also generates a sequence of values;#How do I define a generator? #method One: Use the yield keyword in the function; classCount_down (n): whileN>0:yieldN N-=1#Create a Builder objectc = Count_down (10) #__next__ () method call Builder;>> c.__next__() 10#the Builder object provides a close () method to avoid partial consumption;#that is, when you stop using the generator, the close () method is called automatically; classCount_down (n):Try: whileN>0:yieldN N-=1exceptGeneratorexit:Print('catch an exception to exit!') C= Count_down (10) forIinchC:Print(i)ifI==5: Break>> ...#loop output to 5>>'catch an exception to exit!' #the generator implements a simple co-process defCoroutine (func):defstart (): G=func () g.next ()returngreturnStart @coroutinedefreceiver (): whiletrue:n=yield Print("Got%s"%N) R=receiver () r.send ('Hello World')
Generators and co-processes | Python