1.代码如图所示小白python疑难|TypeError: instance has no next() method

>>> class MyNumbers:
	def __iter__(self):
		self.a = 1
		return self
	def __next__(self):
		if self.a <= 20:
			x = self.a
			self.a += 1
			return x
		else:
			raise StopIteration

		
>>> myclass = MyNumbers()
>>> myiter = iter(myclass)
>>> for x in myiter:
	print(x)

2.出现错误:

Traceback (most recent call last):
  File "<pyshell#134>", line 1, in <module>
    for x in myiter:
TypeError: instance has no next() method

3.解决方法:将def __next __(self): 改成 def next(self): 后,代码可以在python2.7.12中运行了。
(1)要修改的代码块:
小白python疑难|TypeError: instance has no next() method
(2)修改后的代码块及其结果:
小白python疑难|TypeError: instance has no next() method

>>> class MyNumbers:
  def __iter__(self):
    self.a = 1
    return self

  **def next(self):**   
    if self.a <= 20:
      x = self.a
      self.a += 1
      return x
    else:
      raise StopIteration

>>> myclass = MyNumbers()
>>> myiter = iter(myclass)
>>> for x in myiter:
	print(x)

相关文章: