標籤:opened star bre odi pycharm print src lin 迭代
函數體內含有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@decodef 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‘))
View Code
#x=yield
#g.send(‘1111‘),先把1111傳給yield,由yield賦值給x
# 然後再往下執行,直到再次碰到yield,然後把yield後的傳回值返回
grep應用
import osdef init(func): def wrapper(*args,**kwargs): res=func(*args,**kwargs) next(res) return res return wrapper@initdef 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)@initdef 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))@initdef 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@initdef 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)@initdef 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)
View Code
面向過程的程式設計:是一種流水線式的編程思路,是機械式
優點:
程式的結構清晰,可以把複雜的問題簡單
缺點:
1 擴充性差
應用情境:
1 linux核心,git,httpd
python函數(五)—yield的運算式形式