python - 在 Python 3 中 generator.next() 是可见的吗?

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

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() 是该规则的少数异常(exception)之一。这已在 Python 3.0 中修复。 [*]

但不要调用 g.__next__(),而是使用 next(g) .

[*] 还有其他特殊属性已得到此修复; func_name,现在是 __name__,etc.

https://stackoverflow.com/questions/1073396/

相关文章:

linux - 如何使用 sudo 将输出重定向到我无权写入的位置?

python - 连接两个一维 NumPy 数组

linux - 在 Bash 脚本中通过管道传入/传出剪贴板

python - 如何判断 tensorflow 是否从 python shell 内部使用 gpu

linux - 如何将输出重定向到文件和标准输出

python - 创建单独变量字典的更简单方法?

python - Pandas 'count(distinct)' 等效

python - 如何正确确定当前脚本目录?

linux - 杀死分离的 screen session

python - 下标序列时Python中的::(双冒号)是什么?