我试图弄清楚如何使这个类在Python 3中工作,它在Python 2中工作,这是D.Beasley编写的生成器教程中的内容。我是Python的新手,我只是在网上学习教程。
Python 2
class countdown(object):
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def next(self):
if self.count <= 0:
raise StopIteration
r = self.count
self.count -= 1
return r
c = countdown(5)
for i in c:
print i,Python 3,不工作。
class countdown(object):
def __init__(self, start):
self.count = start
def __iter__(self):
return self
def next(self):
if self.count <= 0:
raise StopIteration
r = self.count
self.count -= 1
return r
c = countdown(5)
for i in c:
print(i, end="")发布于 2017-01-07 17:49:05
迭代器的特殊方法从next重命名为Python 3中的__next__,以匹配其他特殊方法。
通过使用以下next的定义,您可以使它在两个版本上工作,而无需更改代码:
__next__ = next因此,每个版本的Python都会找到它所期望的名称。
https://stackoverflow.com/questions/41524531
复制相似问题