1. Generator functions
The difference between a generator function and a normal function is that
1. Use yield instead of return in the generator function, and yield can be called multiple times
2. When the function runs to yield, the yield current state is preserved, waiting for the next next
Usage examples:
def Test (): yield 1 yield 2 yield 3a=test () b=a.__next__( C=a.__next__() d=a.__next__()#print (b) Print (c) Print (d)
In the test function, there are three yield, each using the next method, after the function to a yield, respectively, using BCD to receive the return value,
2. Benefits of Generator functions
Kazuo Generator, the advantage is that you can always do the arithmetic,
Compare with the normal function:
def Shengchengqi (): for in range (10000): yield' This is the first%s egg ' %ia= Shengchengqi () b=a.__next__()print(b)
Generator function, when you do the next function, only to perform the operation, each operation to take a data into the memory, so that can save memory space
If it's a normal function,
def Putonghanshu (): S1=[] for in range (10000): Print (' This is the first%s egg ' %i) a=putonghanshu ()
As long as the function is running, all 10,000 of the data is put into memory, which makes it easy to occupy space.
PS: Question: In this case, the generator function is not very complex, every time you run a piece of code to write.
Introducing A For loop
3. Introducing a generator function into a for loop
Write a generator function
If the generator function runs, it will get a return value from yield, which we can receive with ABC.
You can then use the next method on the generator function to move the cursor within the function to the next yield, which is the only way to find the value to receive.
def Shengchengqi (): for in range (10000): yield' This is the first%s egg ' %ia= Shengchengqi () for inch A: Print (b)
This is automatically run,
Analysis: A=func ()., start running the function, at this point i=0, the cursor after yield.
For the concept of the For loop, add ITER to one object, then one by using the next method until an exception is required, and then return, in the For loop, B directly receives the value after next.
4. Concurrent runs
Requirements Analysis: Two functions, one function calls another function, and then saves the state in such a way.
defChibaozi (name):Print('I'm starting to eat buns.') while1: Baozi=yield Print('This is the bun I ate.%s'%Baozi)defZuo (): S1=chibaozi ('Yehaibin') s1.__next__() forIinchRange (10): S1.send ('Lvelvelve') Zuo ()
When running Zuo, each cycle, Chibaozi will do one action, and then save the state, which is yield. #其实我现在还不太懂, dig a hole.
2018-06-20-python full stack Development day19-generator function detailed