(1-6) Python function _ generator

Source: Internet
Author: User

Understand:

We first use a popular analogy to understand the next generator, to the restaurant to eat, we ordered the menu, the chef is not a one-time dish are all up, but a dish. The chef here is a generator object. The builder is a Python feature, and Python uses the generator to support deferred operations, producing results only when they are good, rather than producing results immediately.

1. Generator function: General function definition, return result with yield statement instead of return statement, yield statement returns one result at a time, in the middle of each result, the state of the function is suspended so that the next time from where it left to execute

2. Generator expression: Similar to a list, however, the generator returns an object that produces results on demand, rather than building a list of results at a time

3, the learning generator needs to learn the iterator first, to determine whether it is an iterator to see if there is a ITER () and next () method

4, the generator can only traverse once

Demand:

Use the generator to realistic a dot stuffed bun to make a pseudo concurrent small program

Code:

Import TimedefConsumer (name):Print("%s point the bun! "%name) whileTrue:baozi=yield        Print("Bun [%s] came, eaten by [%s]! "%(baozi,name))defproducer (name): C1= Consumer ('Liun') C2= Consumer ('Dyq') C1.__next__() c2.__next__()    Print("Master began to prepare steamed buns! ")     forIinch[I+1 forIinchRange (10)]:        ifi%2 = =0:time.sleep (1)            Print("made 2 buns! ") c1.send (i-1) C2.send (i) Producer ("Liun")

(1-6) Python function _ generator

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.