python函數(五)—yield的運算式形式

來源:互聯網
上載者:User

標籤: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的運算式形式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.