函数体内含有yield关键字,那该函数的执行结果是生成器对象
生成器对象的本质就是迭代器,所以yield的功能是
1.把函数的执行结果做成迭代器
2.可以返回多次值,而return只能返回一次值
3.可以挂起函数的执行
=======================================
yield语句形式 yield 1
yield的表达式形式 x=yield
next(g)
g.send('xxx')
示例
def deco(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper @deco def eater(name): print('%s ready to eat' %name) food_list=[] while True: food=yield food_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('脚趾头1')) print(g.send('脚趾头2')) print(g.send('脚趾头3'))
#x=yield
#g.send('1111'),先把1111传给yield,由yield赋值给x
# 然后再往下执行,直到再次碰到yield,然后把yield后的返回值返回
grep应用
import os def init(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper @init def search(target): while True: search_path=yield g=os.walk(search_path) for par_dir,_,files in g: for file in files: file_abs_path=r'%s\%s' %(par_dir,file) # print(file_abs_path) target.send(file_abs_path) @init def opener(target): while True: 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)) @init def cat(target): while True: file_abs_path,f=yield #(file_abs_path,f) for line in f: tag=target.send((file_abs_path,line)) if tag: break @init def grep(target,pattern): tag=False while True: file_abs_path,line=yield tag tag=False if pattern in line: tag=True target.send(file_abs_path) @init def printer(): while True: file_abs_path=yield print(file_abs_path) x=r'C:\Users\Administrator\PycharmProjects\python17期\day5\a' g=search(opener(cat(grep(printer(),'python')))) print(g) g.send(x)
面向过程的程序设计:是一种流水线式的编程思路,是机械式
优点:
程序的结构清晰,可以把复杂的问题简单
缺点:
1 扩展性差
应用场景:
1 linux内核,git,httpd