使用 yield 不会生成新数字(使用 next 函数)

Using yield won't generate new numbers (Using next function)

我正在尝试使用 yield 在每次迭代中生成新数字,如下所示:

def nextSquare():
    i = 1
  
    # An Infinite loop to generate squares 
    while True:
        yield i*i                
        i += 1  # Next execution resumes 
                # from this point

当我尝试时:

>>> for num in nextSquare():
    if num > 100:
         break    
    print(num)

我得到了想要的输出:

1
4
9
16
25
36
49
64
81
100

但是当我尝试时: next(nextSquare())

它总是产生相同的旧结果。难道我做错了什么?我对按需生成感兴趣,而不是在 for 循环中生成新数字。

正如评论中所建议的那样,每次调用 nextSquare 都会生成一个新的迭代器,因此我将代码更改为:

gen = nextSquare()

next(gen) 的 onDemand 调用产生预期结果。