About yield in Python

Source: Internet
Author: User
About yield in Python

Http://www.cnblogs.com/tqsummer/archive/2010/12/27/1917927.html

http://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/

One, iterator (iterator)

In Python, A For loop can be used for any type in Python, including lists, Ganso, and so on, in fact, the For loop is available for any "iterator object," which is actually an iterator

An iterator is an object that implements an iterator protocol, and the iterator protocol in Python is that an object with the next method advances to the next result, and Stopiteration is thrown at the end of a series of results. Any such object can be iterated with a for loop or other traversal tool in Python, and the iteration tool will invoke the next method at each iteration and catch the stopiteration exception to determine when to leave.

Second, generator (constructor)

The generator function is associated with the concept of an iterator protocol in Python. In short, a function that contains a yield statement is specifically compiled by the genetic builder. When the function is called, they return a generator object that supports the iterator interface. The function may have a return statement, but its purpose is to yield the value.

Unlike normal functions that generate values and exit, the generator functions automatically suspend and pause their execution and state after generating the values, and his local variables will hold state information that will be valid again when the function resumes

About yield in Python

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.