In this chapter we will discuss some of the generator yield
Features of 1.yield: delayed result creation
* Generator function: Also uses DEF definitions, but returns with yield, and each return returns only one result, suspending and continuing their state between each resulting result (that is, when there are three results returned, the first result is returned, but the second result is not returned, but because it is yield, It records the state of all scopes and variables when the first result is returned, so that when the second result needs to be returned, it will continue to calculate the state of the previous one.
As can be seen from the above code, yield returns an iterator, and when it returns a result, it automatically records the current scope and the state of the variable, allowing the next result to continue the last calculated state.
2.yield vs Return
The yield example continues with the code above:
>>> def Test (n): for x in range (n): Yield x>>> x=test (3) >>> next (x) 0>>> next (x) 1>& Gt;> Next (x) 2
Here we give the return code:
>>> def Test (n): for x in range (n): Return x>>> Test (3) 0>>> x=test (3) >>> next (x) Traceback (most recent): File "<pyshell#16>", line 1, in <module>
In contrast to the above two sets of code, yield does not have to say again, return an iterator, and return, returned is an integer, and after the first time after execution he jumped out of the loop, no longer continue
The generator function is the same as the regular function, and it uses the DEF definition, but it automatically implements the iterative protocol when it is created.
Summary: This chapter focuses on the characteristics of the generator yield and the difference between the return
This chapter is here, thank you.
------------------------------------------------------------------
Click to jump 0 basic python-Catalogue
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
0 Fundamentals python-19.5 Replay iterator: Generator yield