Python使用迭代器捕获Generator返回值的方法

yipeiwu_com7年前Python基础

本文实例讲述了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

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python数据结构与算法教程》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

相关文章

python函数参数*args**kwargs用法实例

python函数参数*args**kwargs用法实例

复制代码 代码如下:#coding=utf8__author__ = 'Administrator' # 当函数的参数不确定时,可以使用*args和**kwargs。*args没有key...

Python实现的金山快盘的签到程序

复制代码 代码如下:__author__ = 'clownfish'#coding:utf-8import urllib2,urllib,cookielib,json username...

Python中的引用和拷贝浅析

If an object's value can be modified, the object is said to be mutable. If the value cannot b...

详解Python匿名函数(lambda函数)

匿名函数lambda Python使用lambda关键字创造匿名函数。所谓匿名,意即不再使用def语句这样标准的形式定义一个函数。这种语句的目的是由于性能的原因,在调用时绕过函数的栈分配...

Python Logging 日志记录入门学习

Python Logging原来真的远比我想象的要复杂很多很多,学习路线堪比git。但是又绕不过去,alternatives又少,所以必须要予以重视,踏踏实实认认真真的来好好学学才行。...