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