在 python3的产量生成器中没有 next()函数

这个问题中,我使用 Python 生成器得到了无穷无尽的序列。但是同样的代码在 Python3中不起作用,因为它似乎没有 next()函数。next函数的等价物是什么?

def updown(n):
while True:
for i in range(n):
yield i
for i in range(n - 2, 0, -1):
yield i


uptofive = updown(6)
for i in range(20):
print(uptofive.next())
42145 次浏览

In Python 3, use next(uptofive) instead of uptofive.next().

The built-in next() function also works in Python 2.6 or greater.

In Python 3, to make syntax more consistent, the next() method was renamed to __next__(). You could use that one. This is explained in PEP 3114.

Following Greg's solution and calling the builtin next() function (which then tries to find an object's __next__() method) is recommended.