Found that there are many people do not understand yield, foggy, and then try to express in words.
as long as the function contains a yield statement, it returns a generatorSo instead of seeing it as a function definition, we think of it as
Generator Definition. function with
returnReturned, and the generator
yieldReturn.
Next comes the act of yield.
Like what
def html (): yield ' header ' for I in range (5): yield i- yield ' footer ' H = HTML () #此时h变量就是一个生成器. For x in H: #遍历 Generator Print X
How do you understand this function?
Use
"yield elimination Technology", use a result variable to collect the yield and return it.
Then converted into
def html (): ret = [] ret.append (' header ') for I in range (5): ret.append (i) ret.append (' footer ') return RET
As you can see, the yield statement is gone and everything is in the RET sequence.
and
powerful magic of the generatorIs that it is deferred execution, it executes the code when needed, it "remembers" where the yield is executed, and when it gets the next result, it goes down from the last yield position.
So the generator is relative to the list, it saves only one current result at a time, saves memory, the disadvantage is that the subscript index cannot be used, and the traversal is gone. Another benefit is that you can generate infinite sequences, such as cycle.
It is important to note that when we call a function, it does not start executing the function body code, but returns a generator.
Like what
Def A (): print ' hehe ' yield 1 yield 2
When we are a (), it does not print ' hehe ', but only when we traverse it, it begins to execute, from the first line of code in the function body to the first yield, and then continues to execute the code to the next yield, so go on.
Elegant Python-yield Concise Tutorial