python3.x中的生成器generator调用next方法

来源:互联网 发布:单片机模块化编程教程 编辑:程序博客网 时间:2024/06/06 00:48


python3.x中的生成器generator调用next方法


  • 编辑
  • 删除

今天写了一段Python程序,用到了Python的generator。当我用到generator的next方法时,shell总是提醒我符号错误。当时我是这么用的:

[python] view plain copy print?
  1. def fib(max):  
  2.     n,a,b=0,0,1  
  3.     while(n<max):  
  4.         yield b  
  5.         a,b=b,a+b  
  6.         n+=1  

[python] view plain copy print?
  1. g=fib(5)  
  2. g.next()  

[python] view plain copy print?
  1. >>> f.next()  
  2. Traceback (most recent call last):  
  3.   File "<pyshell#24>", line 1in <module>  
  4.     f.next()  
  5. AttributeError: 'generator' object has no attribute 'next'  
上面的错误信息的大致意思是“generator”没有next属性。这是怎么回事儿呢? 于是,我登录Python官方网站上一看究竟。后来我才发现,前两天闲着没事儿,我把之前Python2.7更新到Python3.4,。而Python2.x与Python3.x在一些语法特性上有所不同。比如我上面的next方法调用错误。在Python3.x中若使用generator的next属性,应该这么调用:

[python] view plain copy print?
  1. g=fib(4)  
  2. next(g) #与之前的g.next()不同  

好吧,既然已经更新到Python3.4了,那就好好看看Python3.x的新特性吧。

这是Python官方公布的Python3.x 的新特性的文档:https://docs.python.org/3.2/whatsnew/3.2.html


原创粉丝点击