但是用for迴圈呼叫generator時,發現拿不到generator的return語句的返回值。如果想要拿到返回值,必須捕獲StopIteration錯誤,返回值包含在StopIteration的value中:
#!/usr/bin/env python # -*- coding: utf-8 -*- def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done' # 捕獲Generator的返回值 g = fib(6) while True: try: x=next(g) print('g=',x) except StopIteration as e: print('Generrator return value:', e.value) break
輸出:
g= 1 g= 1 g= 2 g= 3 g= 5 g= 8 Generrator return value: done