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