Define a function in which the function is paused with yield, then this function is a generator. The generator returns an iterator.
The difference between yield and return:
1. When the function is executed, the function ends when the return is reached. Execution to yield, pause, if yield is followed by a statement, the next call to the __next__ () method can continue the last call execution.
2. Execute the method: After the function definition, the function name is executed after the parentheses. However, if it is a generator, the parentheses after the function name do not execute the function and need to be executed using the __next__ () method of the generator.
That is, the function name (). __netx__ ()
3. Return returns the value of the function, yield does not return the function value, just pauses the function.
#--encoding:utf-8--def cash_out (amount): While amount > 0: Amount-=- print ("Before:" + str (amount)) #return Amount yield "function pause" print ("After:" + str (amount)) print ("Get the Money Again") ATM = Cash_out ( ATM) print (atm.__next__ ()) print ("Leave to do something ...") print ("20 years later ...") Print (atm.__next__ ())
Output Result:
D:\Python34\python.exe e:/pycharmprojects/day3/opentest.py
<generator Object Cash_out at 0x02f35c10>
before:400
Function paused
Leave to do something ...
20 years later ...
after:400
We're taking the money again.
before:300
Function paused
Note: As you can see, after the first call to the __next__ () method, the function pauses, after printing "20 years ...", call the __next__ () method again, and the function then resumes execution at the last yield pause. Yield is equivalent to a breakpoint on a function.
Iterators and generators