在Python 3中是否可以看到generator.next()? [英] Is generator.next() visible in 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行为差异的东西.
g.next()
已重命名为g.__next__()
.原因是一致:__init__()
和__del__()
之类的特殊方法都具有双下划线(在当前情况下为"dunder"),而.next()
是该规则的少数例外之一.这已在Python 3.0中修复. [*]
但不要使用 next(g)
. /p>
[*]还有其他特殊属性可以解决此问题; func_name
,现在是__name__
,等.
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.
g.next()
has been renamed to g.__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__()
, use next(g)
.
[*] There are other special attributes that have gotten this fix; func_name
, is now __name__
, etc.
这篇关于在Python 3中是否可以看到generator.next()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!