Python: Generator function

Source: Internet
Author: User
Tags generator

generator function : a function containing yield statements;

Builder Object : The Builder object behaves similarly to the iterator object and supports an iterative interface: __next__ (), which requires an iterative protocol ' if you want to execute the internal statement of the generator function.

a, when the generator function is called , does not execute the function inner statement, but returns a generator object;

B, each execution of a statement, returns a corresponding yield value, although the function is a yield temporarily returned value, but retains the state of the program run, that is, when executing g.__next__ (), the execution of the function statement, and return the second yield corresponding value When all yield return values are executed, the program throws a stop iteration exception: stopiterstion; This behavior, like iterators, implements an interface for iterators.

deff ():Print('in F (), 1')    yield1Print('in F (), 2')    yield2Print('in F (), 3')    yield3g=f ()Print(g)#output: <generator object F at 0x056f8210>Print(g.__next__())#output: In F (), 11Print(g.__next__())#output: In F (), 22Print(g.__next__())#output: In F (), 33Print(g.__next__())#Output: Stopiteration

C, the Generator object is also an iterative object, that is, it can be placed in the for loop after the in, then the generator object implements the __iter__ () method, returns itself;

 for inch g:     Print (x)
# output: In F (), 1 1 in f (), 2 2 in F (), 3 3

D, the Generator object implements the iterator interface (__next__ ()), and implements an iterative interface (__ITER__ ()), which returns itself;

Print (g.__iter__ is g)

# Output True

Python: Generator function

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.