The function body contains the yield keyword, and the result of the function is the generator object
The essence of the builder object is the iterator, so the yield function is
1. Make an iterator to the execution result of the function
2. Multiple values can be returned, and return can only return one value at a time
3. Can suspend the execution of functions
=======================================
Yield statement Form yield 1
The expression form of yield X=yield
Next (g)
G.send (' xxx ')
Example
defDeco (func):defWrapper (*args,**Kwargs): Res=func (*args,**Kwargs) Next (res)returnResreturnWrapper@decodefEater (name):Print('%s ready to eat'%name) food_list=[] whileTrue:food=yieldfood_list food_list.append (food)Print('%s start to eat%s'%(Name,food)) G=eater ('Alex')#Print (g)#Next (g) #等同于 g.send (None)Print(G.send ('Toes 1'))Print(G.send ('Toes 2'))Print(G.send ('Toes 3'))View Code
#x =yield
#g. Send (' 1111 '), pass 1111 to yield, assign value to X by yield
# and then proceed down until the yield is hit again, and return the return value after yield
grep application
ImportOSdefInit (func):defWrapper (*args,**Kwargs): Res=func (*args,**Kwargs) Next (res)returnResreturnWrapper@initdefSearch (target): whileTrue:search_path=yieldg=Os.walk (Search_path) forPar_dir,_,filesinchg: forFileinchFiles:file_abs_path=r'%s\%s'%(Par_dir,file)#print (File_abs_path)target.send (file_abs_path) @initdefopener (target): whileTrue:file_abs_path=yield #print (' Opener func==> ', File_abs_path)With open (file_abs_path,encoding='Utf-8') as F:target.send ((file_abs_path,f)) @initdefCat (target): whiletrue:file_abs_path,f=yield #(file_abs_path,f) forLineinchF:tag=Target.send ((file_abs_path,line))iftag: Break@initdefgrep (target,pattern): Tag=False whileTrue:file_abs_path,line=yieldtag Tag=FalseifPatterninchLine:tag=True target.send (file_abs_path) @initdefprinter (): whileTrue:file_abs_path=yield Print(file_abs_path) x=r'C:\Users\Administrator\PycharmProjects\python17 period \day5\a'g=search (Opener (Cat (grep) (printer (),'python'))))Print(g) g.send (x)View Code
Process-oriented programming: is a pipeline of programming ideas, is a mechanical
Advantages:
The structure of the program is clear, can make complex problems simple
Disadvantages:
1 Poor extensibility
Application Scenarios:
1 Linux kernel, git,httpd
Python function (v)-yield expression form