Python yield usage

Source: Internet
Author: User

When yield is used in a function, the function does not return data, but instead returns a Generator object (Generator object), which actually runs when the loop is traversed to get the actual value.

Example one is the example I see in a book, and the second is the example I have simplified, which makes no difference in functionality.

#示例一: Def filereadlines ():    seek = 0    while  True:        with open ('/home/python/passwd ',  ' r ')  as  f:            f.seek (Seek)              data = f.readline ()              if data:                 seek = f.tell ()                  yield data             else:                 return                 For item in filereadlines ():     print (item) #示例二: Def filereadline ():     with open ('/home/python/passwd ',  ' r ')  as f:         for line in f:             yield linefor item in filereadline ():    print (item)


This article is from the "Daibayang blog" blog, make sure to keep this source http://daibaiyang119.blog.51cto.com/3145591/1947290

Python yield usage

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.