生成器與協程 | Python
阿新 • • 發佈:2018-01-18
while close got def style for 停止 () 使用
# 生成器與協程 # 生成器是一種特殊的叠代器,它同樣生成一個值的序列; # 如何定義生成器? # 方法一:函數中使用yield關鍵字; class count_down(n): while n>0: yield n n-=1 # 創建一個生成器對象 c = count_down(10) # __next__()方法調用生成器; >> c.__next__() 10 # 生成器對象提供了close()方法,來避免部分消耗; # 即:停止使用生成器時,就會自動調用close()方法;class count_down(n): try: while n>0: yield n n-=1 except GeneratorExit: print(‘捕捉到退出的異常!‘) c = count_down(10) for i in c: print(i) if i==5: break >> ... # 循環輸出至5 >> ‘捕捉到退出的異常!‘ # 生成器實現簡單的協程 def coroutine(func): def start(): g = func() g.next() return g return start @coroutine def receiver(): while True: n = yield print("Got %s"%n) r = receiver() r.send(‘hello world‘)
生成器與協程 | Python