Iterators and generators

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.