pythonのyield

1338 ワード

ずっとyieldを使わないで、今日勉強します.
 def fab(max): 
    n, a, b = 0, 0, 1 
    while n < max: 
        yield b 
        # print b 
        a, b = b, a + b 
        n = n + 1

関数にyieldがある場合、関数は関数ではなくジェネレータです.yieldはreturnに似ていますが、関数から飛び出すのではなく、反復値を返します.
 >>> for n in fab(5): 
 ...     print n

関数の使い方は、ループするとyieldに実行され、値が返され、次のループするとyieldの次のデータから実行され、yieldに遭遇するまでループします.
 >>> f = fab(5) 
 >>> f.next() 
 1

もちろんこのように呼び出すこともできます.
returnがない場合、関数は完了まで実行され、returnがある場合は、StopIterationを直接投げ出して反復を終了します.
 def read_file(fpath): 
    BLOCK_SIZE = 1024 
    with open(fpath, 'rb') as f: 
        while True: 
            block = f.read(BLOCK_SIZE) 
            if block: 
                yield block 
            else: 
                return

ビッグデータを読み込むと役に立ちます.
戻り期間
import datetime

def main(start, end):
    start_time = datetime.datetime.strptime(start, "%Y-%m-%d")
    end_time = datetime.datetime.strptime(end, "%Y-%m-%d")

    while start_time <= end_time:
        yield start_time
        start_time += datetime.timedelta(days=1)

if __name__ == '__main__':
    for i in main('2013-02-01', '2013-02-28'):
        print i, type(i)