标签:res lte 1.3 yield att img div gre bsp
基础篇
本章大纲:
def eater(name): print(‘%s 开始吃了‘ %name) while True: food=yield print(‘%s开始吃%s‘%(name,food)) g=eater(‘alex‘) next(g)
断点分析为什么需要next()
第一步用next作用:
a,因为yeild的原因程序肯定是暂停的。只有next程序才能执行。
b,而send是先发送一个值给yeild然后在next,显然程序都不能开始了。从何说起接收send发送的值呀。所以第一步next让程序先走到yeild停等待send发值状态
第二步send作用:
a,通过send把值发送给暂停的yeild
b,当yeild接收到了send发送的值,他会自动next()一次生成器
def eater(name): print(‘%s 开始吃了‘ %name) list1=[] while True: food=yield list1 print(‘%s开始吃%s‘%(name,food)) list1.append(food) g=eater(‘alex‘) next(g) res=g.send(‘苹果‘) res=g.send(‘橘子‘) res=g.send(‘香蕉‘) print(res)
def zhuangshi(func): def neibu(*args,**kwargs): g=func(*args,**kwargs) next(g) return g return neibu @zhuangshi #eater=neibu def eater(name): print(‘%s 开始吃了‘ %name) list1=[] while True: food=yield list1 print(‘%s开始吃%s‘%(name,food)) list1.append(food) g=eater(‘alex‘) res=g.send(‘苹果‘) res=g.send(‘橘子‘) res=g.send(‘香蕉‘) print(res)
1.5 利用yeild实现grep -rl ‘python‘ /root
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)
标签:res lte 1.3 yield att img div gre bsp
原文地址:http://www.cnblogs.com/tiantao36/p/6936399.html