本文实例讲述了Python使用迭代器捕获Generator返回值的方法。分享给大家供大家参考,具体如下:
用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