Generator.next() 在 Python 3 中可见吗?
我有一个生成一系列的生成器,例如:
def triangle_nums():
'''Generates a series of triangle numbers'''
tn = 0
counter = 1
while True:
tn += counter
yield tn
counter += + 1
在Python 2中,我可以进行以下调用:
g = triangle_nums() # get the generator
g.next() # get the next value
但是在Python 3中,如果我执行相同的两行代码,我会收到以下错误:
AttributeError: 'generator' object has no attribute 'next'
但是,循环迭代器语法确实在 Python 3 中工作时,
for n in triangle_nums():
if not exit_cond:
do_something()...
我还没有找到任何可以解释 Python 3 行为差异的内容。
I have a generator that generates a series, for example:
def triangle_nums():
'''Generates a series of triangle numbers'''
tn = 0
counter = 1
while True:
tn += counter
yield tn
counter += + 1
In Python 2 I am able to make the following calls:
g = triangle_nums() # get the generator
g.next() # get the next value
however in Python 3 if I execute the same two lines of code I get the following error:
AttributeError: 'generator' object has no attribute 'next'
but, the loop iterator syntax does work in Python 3
for n in triangle_nums():
if not exit_cond:
do_something()...
I haven't been able to find anything yet that explains this difference in behavior for Python 3.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
g.next()
已重命名为g.__next__()
。 这样做的原因是一致性:像__init__()
和__del__()
这样的特殊方法都有双下划线(或者当前白话中的“dunder”),并且.next()
是该规则的少数例外之一。 这个问题在 Python 3.0 中得到了修复。 [*]但不要调用
g.__next__()
,而是使用下一个(g)
。[*] 还有其他特殊属性已得到此修复;
func_name
,现在是__name__
,等等g.next()
has been renamed tog.__next__()
. The reason for this is consistency: special methods like__init__()
and__del__()
all have double underscores (or "dunder" in the current vernacular), and.next()
was one of the few exceptions to that rule. This was fixed in Python 3.0. [*]But instead of calling
g.__next__()
, usenext(g)
.[*] There are other special attributes that have gotten this fix;
func_name
, is now__name__
, etc.尝试:
查看这张整洁的表格 显示了 2 和 3 之间的语法差异。
Try:
Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.
如果您的代码必须在 Python2 和 Python3 下运行,请使用 2to3 six 库,如下所示:
If your code must run under Python2 and Python3, use the 2to3 six library like this: