python学习--如何实现可迭代对象(itearable)和迭代器(iterator)

关于可迭代对象Iterable 和迭代器对象iterator

可迭代对象:可以直接作用于for循环的对象统称为可迭代对象:Iterable。 可迭代对象包含一个__iter__方法,或__getitem__方法,其中__iter__方法会返回一个迭代器iterator。

      可迭代对象一类是集合数据类型,如list,tuple ,dict, set,str,  另一类可迭代对象是生成器generator。

迭代器对象:可以作用于next()函数的对象都是迭代器对象。迭代器对象必须实现__next__方法。

for循环时候,如果循环的是个可迭代对象Iterable,会调用Iterable的__iter__方法,返回一个迭代器,然后调用他的next方法,直到遇到StopIteration异常跳出循环。

      如果循环的是一个迭代器对象,就直接调用next方法,知道遇到StopIteration异常跳出循环。

先生成一个迭代器对象,再生成一个可迭代对象

from collections import Iterator,Iterable
class AIterator(Iterator):
  def __init__(self, s, e):
    self.current = s
    self.end = e
  # def __iter__(self):
    # return self
  def __next__(self):
    if self.current < self.end:
      self.index = self.current
      self.current += 1
      return self.index
    else:
    raise StopIteration
class AIterable:
  def __init__(self,s,e):
    self.s=s
    self.e=e
  def __iter__(self):
    return AIterator(self.s,self.e)

it = AIterator(1,10)
iteable=AIterable(2,5)
for i in it:
print(i)

原文地址:https://www.cnblogs.com/daacheng/p/7923325.html