Generator
The function that you write yourself
A simple generator function
As long as the __next__ () function and _iter__ () are included in the generator
Def genetator (): print (1) return ' a ' ret = Genetator () print (ret) Result: 1a
As long as the function containing the Yeild keyword is a generator function and is not shared with return and needs to be written inside the function
Def genetator (): print (1) yield ' A ' # generator function: After execution you get a build as a return value ret = Genetator () print (ret) #结果: <generator Object Genetator at 0x0225dcc0>print (ret.__next__ ()) # Result: # aret.__iter__ ()
Def Wahaha (): For i in range: yield ' Wahaha%s '%ig=wahaha () #只拿前五个, with count count = 0for k in g: count + = 1 Print (k) if Count > 5: break# can take another value print at any time (' Ooooo ', g.__next__ ())
Each generation of generators is unrelated to each other, and each execution
Example of listening file input (generator)
# Listen for input to the file
def tail (filename): f = open (filename,encoding= ' utf-8 ') while True: line = F.readline () if Line.strip (): print (' * * * ', line.strip ()) tail (' info ')
#监听文件的输入, and filter the content
def tail (filename): f = open (filename,encoding= ' utf-8 ') while True: line = F.readline () if Line.strip (): yield Line.strip () g = tail (' info ') for I in G: " if ' python ' in I: print (' ****** ', I, ' ~ ~ ~ ~ ')" C18/>if ' www ' in I: print (' ****** ', I, '!!!! ')
10-4 Generators