Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/365.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
generator.next()在Python 3中可见吗?_Python_Python 3.x_Iteration - Fatal编程技术网

generator.next()在Python 3中可见吗?

generator.next()在Python 3中可见吗?,python,python-3.x,iteration,Python,Python 3.x,Iteration,我有一个生成序列的生成器,例如: 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 gene

我有一个生成序列的生成器,例如:

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'
但是,循环迭代器语法在Python3中确实有效

for n in triangle_nums():
    if not exit_cond:
       do_something()...
我还没有找到任何东西来解释Python 3的这种行为差异。

试试:

next(g)
查看显示2和3之间语法差异的内容。

g.next()
已重命名为
g。原因是一致性:像
\uuu init\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()
这样的特殊方法都。这在Python 3.0中得到了修复。[*]

但是不要调用
g.\uuuuu next\uuuu()
,而是使用


[*]还有其他特殊属性得到了此修复
func_name
,现在是
\uuu name\uu

如果您的代码必须在Python2和Python3下运行,请像这样使用2to3库:

import six

six.next(g)  # on PY2K: 'g.next()' and onPY3K: 'next(g)'

@MaikuMori I修复了链接(等待同行修改)(该站点似乎已关闭。镜像站点仍处于活动状态)再次修复了链接。更完整,顺便说一句。除了
g.next()
应该是
g
?适用于错误“generator”对象没有属性“next”。除非您需要支持早于2.6的Python版本,否则不需要太多属性。Python2.6和2.7具有
next
内置函数。你知道Python2为什么在这些方法中首先避开了dunder约定吗?这可能只是一个疏忽。当你在类中重写str时会怎么样?它会改变str(obj)还是_str(obj)?@NoName是的,你会。@MatthewMilone五年后的政治公众人物计划中提到了它。