Generators and co-processes | Python

Source: Internet
Author: User
Tags generator

#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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.