Today, when reading code from other colleagues, I found a python keyword that has never been used: yield.
I first asked my colleague, and heard him say a few words. I had a vague impression that it was just fuzzy. So I searched for the information myself. After reading for a long time, I gradually became clear. However, I am still confused about the working mechanism and application. Well, write down the initial impression.
Yield is simply a Generator ). The generator is a function that remembers the position in the function body during the last return. The second (or NTH) Call to the generator function jumps to the center of the function, while all local variables in the last call remain unchanged.
You can see that a function contains yield, which means that this function is already a Generator and its execution will be much different from other common functions.
You may be confused here. Let's take a look at some instances first:
Copy codeThe Code is as follows:
Def test (data_list ):
For x in data_list:
Yield x + 1
Data = [1, 2, 4]
For y in test (data ):
Print y
The output result is:
2 3 4 5
Another usage:
Handle = test (data)
Handle. next () Output 2
Handle. next () Output 3
Handle. next () output 4
Handle. next () Output 5
Handle. next () will report an error
This is just the initial impression of yield.