我试图弄清楚如何使这个类在Python3中工作,它在Python2中工作。这是D.Beasley的发电机教程。我是Python的新手,正在学习在线教程。在
Python2
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,
Python3,不工作。在
^{pr2}$
在python3中,迭代器的特殊方法从
next
重命名为__next__
,以匹配其他特殊方法。在通过遵循
next
的定义,您可以使它在两个版本上都工作,而无需更改代码:因此,Python的每个版本都会找到它期望的名称。在
相关问题 更多 >
编程相关推荐