如何在python中使用uuu iter_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?
我正在根据网站上的教程学习python中迭代器、生成器和装饰器的工作原理 在第一个示例中,他/她演示了一个简单的示例,如下所示:如何在python中使用uuu iter_uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu?,python,python-2.7,iterator,iteration,Python,Python 2.7,Iterator,Iteration,我正在根据网站上的教程学习python中迭代器、生成器和装饰器的工作原理 在第一个示例中,他/她演示了一个简单的示例,如下所示: class Count: def __init__(self, low, high): self.low = low self.high = high def __iter__(self): return self def __next__(self): if self.cur
class Count:
def __init__(self, low, high):
self.low = low
self.high = high
def __iter__(self):
return self
def __next__(self):
if self.current > self.high:
raise StopIteration
else:
self.current +=1
return self.current -1
问题是,我无法迭代此类的对象:
>>> ================================ RESTART ================================
>>>
>>> c = Count(1, 10)
>>> for i in c:
print i
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
for i in c:
TypeError: instance has no next() method
>>>
重新启动================================
>>>
>>>c=计数(1,10)
>>>对于c中的i:
打印i
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
对于c中的i:
TypeError:实例没有next()方法
>>>
怎么了?该教程似乎是针对Python3的 在Python2中,迭代器必须具有以下方法(-Renaming iterator.next()to iterator.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()):
该教程似乎是针对Python3的 在Python2中,迭代器必须具有以下方法(-Renaming iterator.next()to iterator.\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu()):
非常感谢。无论如何,为什么我没有收到
self.current
的未定义变量错误?当行self.current+=1
第一次运行时,它的值是多少?@Abraham我认为它应该是self.current=low
@Abraham:您确实会得到一个错误。您应该在@Abraham中初始化self.current
——如果将self.current
打印为next()的第一条语句,您会得到什么
?将函数中的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
重命名为next
的另一种解决方案是切换Python解释器,以便按照教程的预期使用Python 3。Python3的许多方面都比Python2好,最显著的是它对Unicode文本的处理。有一些模块只适用于Python 2,但数量正在稳步减少,因此,除非您确定已经需要其中一个模块,否则我建议您先学习Python 3,而不是先学习Python 2,然后再学习如何将代码移植到Python 3。谢谢。无论如何,为什么我没有收到self.current
的未定义变量错误?当行self.current+=1
第一次运行时,它的值是多少?@Abraham我认为它应该是self.current=low
@Abraham:您确实会得到一个错误。您应该在@Abraham中初始化self.current
——如果将self.current
打印为next()的第一条语句,您会得到什么
?将函数中的\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu
重命名为next
的另一种解决方案是切换Python解释器,以便按照教程的预期使用Python 3。Python3的许多方面都比Python2好,最显著的是它对Unicode文本的处理。有一些模块只适用于Python2,但数量正在稳步减少,因此,除非您确定已经需要其中一个模块,否则我建议您先学习Python3,而不是先学习Python2,然后再学习如何将代码移植到Python3。
class Count:
def __init__(self, low, high):
self.current = low
self.high = high
def __iter__(self):
return self
def next(self):
if self.current > self.high:
raise StopIteration
else:
self.current +=1
return self.current -1