Python Yield Learning Notes

Source: Internet
Author: User

Before learning yield, we learned about the concept of iterators and generators. Not too much refinement.

Iterator objects: Supports the ITER and Next () method where the iter() method returns the iteration object itself, the next () method returns the next element of the container, and the stopiteration exception is issued at the end.

The builder is an iterator, but can only be traversed once.

Yield return is the generator.

Look at the example, the Bank builder.

#-*-Coding:utf-8-*-
"" "
Created on Fri Dec 13:30:07 2015

@author: Weeds" ""

Class Bank ():
    C Risis = False
    def create_atm (self): While not
        self.crisis:
            yield "$"

HSBC = Bank ()
Corner_ STREET_ATM = HSBC.CREATE_ATM () print
corner_street_atm.next () print

corner_street_atm.next () print
[ Corner_street_atm.next () for cash in range (5)]

hsbc.crisis = True

#print corner_street_atm.next ()
wall _STREET_ATM = HSBC.CREATE_ATM ()
#print wall_street_atm.next ()

hsbc.crisis = False
print wall_street_ Atm.next ()
print corner_street_atm.next () print corner_street_atm.next ()

Recently read a Python performance optimization software, more use yield.

Reference articles

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.