1. 程式人生 > 實用技巧 >webApplicationContext 與servletContext的關係(轉載)

webApplicationContext 與servletContext的關係(轉載)

把yield視作控制流程的方式--------------Python協程

一個簡單的協程:

def simple_coroutine():
    print('-> coroutine started')
    x=yield
    print('-> coroutine received:',x)

>>>my_coro=simple_coroutine()
>>>next(my_coro)
-> coroutine started
>>>my_coro.send(42)
-> coroutine received:42
Traceback (most recent call last):
    ...
StopIteration

解釋:

1.呼叫simple_coroutine()函式,返回生成器物件

2.呼叫next()函式,啟動生成器,在yield語句出暫停

3.傳送42,yield表示式會計算出52,然後一直執行到下一個yield表示式,或者終止

4.控制權流動到定義體末尾,生成器丟擲StopIteration異常

一個稍微複雜的案例:

使用協程計算移動平均

def averager():
    total=0.0
    count=0
    average=None
    while True:
        term=yield average
        total+=term
        count
+=1 average=total/count >>>coro_avg=averager() >>>next(coro_avg) >>>coro_avg.send(10) 10.0 >>>coro_avg.send(30) 20.0 >>>coro_avg.send(5) 15.0

裝飾器------自動預激協程的好方法

from functools import wraps
def coroutine(func):
    @wraps(func):
    def primer(*args,**kwargs):
        gen
=func(*args,**kwargs) next(gen) return gen return primer