Python 協程函數

來源:互聯網
上載者:User

標籤:http   tle   strong   init   nbsp   bsp   使用   運行   代碼   

協程函數就是使用了yield運算式形式的產生器

def eater(name):    print("%s eat food" %name)    while True:        food = yield    print("done")g = eater("gangdan")print(g)

結果:
generator object eater at 0x00000000028DC048
這裡就證明了g現在就是產生器函數

1. 2 協程函數賦值過程

用的是yield的運算式形式

要先運行next(),讓函數初始化並停在yield,相當於初始化函數,然後再send() ,send會給yield傳一個值
** next()和send() 都是讓函數在上次暫停位置繼續運行,

next是讓函數初始化

send在觸發下一次代碼的執行時,會給yield賦值
**

def eater(name):    print(‘%s start to eat food‘ %name)    food_list=[]    while True:        food=yield food_list        print(‘%s get %s ,to start eat‘ %(name,food))        food_list.append(food)e=eater(‘鋼蛋‘)  # wrapper(‘‘)# print(e)print(next(e))     # 現在是運行函數,讓函數初始化print(e.send(‘包子‘))  #print(e.send(‘韭菜餡包子‘))print(e.send(‘大蒜包子‘))

這裡的關鍵是:
要先運行next()函數

用裝飾器函數把next()函數先運行一次:

def start(func):    def wrapper(*args,**kwargs):        res=func(*args,**kwargs)  # next()        next(res)     # 這是關鍵        return  res    return wrapper@start   # e = start(e)def eater(name):    print(‘%s start to eat food‘ %name)    food_list=[]    while True:        food=yield food_list        print(‘%s get %s ,to start eat‘ %(name,food))        food_list.append(food)e=eater(‘鋼蛋‘)  # wrapper(‘鋼蛋‘)  print(e.send(‘包子‘))print(e.send(‘韭菜餡包子‘))print(e.send(‘大蒜包子‘))

在@start # e = start(e) 後面寫上,運行start函數,start函數返回wrapper

1.3 協程函數使用裝飾器初始化

這裡主要是為了防止忘記初始化next操作,在裝飾器中添加

def init(func):    def wrapper(*args,**kwargs):        res = func(*args,**kwargs)        next(res)     #  在這裡執行next        return res    return wrapper@init            # eater=init(rater)def eater(name):    print("%s eat food" %name)    food_list=[]    while True:        food = yield food_list        print("%s star to eat %s" %(name,food))        food_list.append(food)    print("done")g = eater("gangdan")# 這裡就不需要nextprint(g.send("1"))print(g.send("2"))print(g.send("3"))print(g.send("4"))

結果:
gangdan eat food
gangdan star to eat 1
[‘1‘]
gangdan star to eat 2
[‘1‘, ‘2‘]
gangdan star to eat 3
[‘1‘, ‘2‘, ‘3‘]
gangdan star to eat 4
[‘1‘, ‘2‘, ‘3‘, ‘4‘]

```
只要用到裝飾器函數,馬上寫裝飾器函數,寫@init馬上想到** eater=init(eater) **,先執行裝飾器函數。

關鍵是next(res),這裡是是對產生器進行初始化。這裡就會只執行一次,執行完後後面啟動並執行都是e.send()

轉載出自:http://www.cnblogs.com/Python666/p/6702422.html

Python 協程函數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.