Simple understanding of the generator

Formula list # 

# DEF f (n-):
# n-return **. 3
#
# X = [f (A) for A in Range (10)] f function first calls #,
# Print (X)


DEF bar ():

Print ( "OK1")
yield 1

Print ( "OK2")
yield 2


S = bar () # Builder is a state of the object can be recorded when performing where he will remember the current execution state, then the next execution time , from where the end of the last started
Print (S)
Print (Next (S))
Print (Next (S))


S = (X **. 3 for X in Range (100000000)) # generated at this time is defined a is
Print (S) # <generator Object <genexpr> AT 0x000000000BAF43B8>

Print (Next (S)) # 0
Print (Next (S)) #. 1


for X in S: # generator itself is an iterator object generator Why provincial memory python itself because there is a garbage collection mechanism, when a variable is not referenced, the variable will be cleared python
Print (the X-)


# 0 0 1 1 2 3 5 8
DEF fib (max):

n , before,after = 0, 0, 1,

while n < max:
yield before

before, after = after, before+after


n = n+1

g=fib(3)
print(g)
print(next(g))




#send method 
DEF Loger ():
COUNT = the yield "qwer"
Print (COUNT)

COUNT = the yield "qwer"

Print (COUNT)


G = Loger () # generated ah is assigned to a variable
a = next (g) # call this generator, and then allowed to return to a variable to receive a variable
Print (a)
# g.send (None) Next # = (G)
B = g.send ( "ABC") # send to use this method, firstly to pass parameters (None) a blank for the generator, because they do not pass parameters, then, send do not know to whom to pass parameters to accept not send can be passed as a parameter generator loger, but first of all we have about the implementation of this generator
print (B)
g.send ( "EFG")


#yield pseudo concurrency

Time Import 
DEF Consumer (name): 
    Print ( "% S ready bun it!"% name) 
    the while True: 
       Baozi = yield 

       Print ( "bun [% s] came, the [% s] to eat!"% ( Baozi, name)) 


DEF Producer (name): 
    C = Consumer ( 'A') 
    C2 = Consumer ( 'B') 
    C .__ Next __ () 
    C2 .__ Next __ () 
    Print ( "! began to prepare baking it") 
    for in the Range i (10): 
        the time.sleep (1) 
        Print ( "! do two buns") 
        c.send (i) 
        c2.send (i) 

Producer ( "alex")


Guess you like

Origin www.cnblogs.com/langjitanya/p/10941526.html