Python 2和3的区别--生成器next

来源:互联网 发布:网络销售的工作总结 编辑:程序博客网 时间:2024/06/01 08:38

日期:20170926


开一新目录来记录Python 2和3的区别。

如果只是简单学Python编程的,可以直接学Python3,因为Python2貌似不更新了。
如果想深入学习Python或者以Python的工作的,那有很大几率会遇到Python 2的代码,所以有必要知道Python 2和3的不同点。
当然,如果要用Python编程,最好选择Python3,因为这是趋势。如果你编Python2,却在另一台机的Python环境出错(现在大多是装Python3),那就尴尬了,对不?

本目录记录的是,我用Python2不能正确运行,而Python3可以的。或者用Python2能正确运行,而Python3不可以的。


Python3生成器没有next()

代码,

#!/usr/bin/python3 #使用Python3def MyGenerator():        yield 1        yield 2        yield 3print(Num.next())print(Num.next())print(Num.next())

运行,

[penx@ali01 python]$ ./example_generator.py Traceback (most recent call last):  File "./example_generator.py", line 9, in <module>    print(Num.next())AttributeError: 'generator' object has no attribute 'next'[penx@ali01 python]$ 

结果,
在代码中,我使用的是Python3运行。
我创建一个生成器实例Num,并调用Num.next()。然后报错,

AttributeError: ‘generator’ object has no attribute ‘next’


Python2可以

我们把运行环境换Python2,
代码,

#!/usr/bin/python #使用Python2def MyGenerator():        yield 1        yield 2        yield 3Num=MyGenerator()print(Num.next())print(Num.next())print(Num.next())

运行,

[penx@ali01 python2]$ ./example_generator.py 123[penx@ali01 python2]$

结果,
正确运行。


小结

Python3生成器next下一个值,用next(Generator)
例如,

#!/usr/bin/python3def MyGenerator():        yield 1        yield 2        yield 3Num=MyGenerator()print(next(Num)) #使用next(Generator)print(next(Num))print(next(Num))