本文實例講述了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= 1g= 1g= 2g= 3g= 5g= 8Generrator return value: done
更多關于Python相關內容感興趣的讀者可查看本站專題:《Python函數使用技巧總結》、《Python數據結構與算法教程》、《Python字符串操作技巧匯總》、《Python入門與進階經典教程》及《Python文件與目錄操作技巧匯總》
希望本文所述對大家Python程序設計有所幫助。
新聞熱點
疑難解答