python自定义迭代器对象以及可迭代对象

# coding=utf8
from collections import Iterator
from collections import Iterable

#迭代器对象
class OwnIteror( Iterator ):
     def __init__(self , arrs ):
          self.index = 0
          self.arrs = arrs
     def  next(self):
          if self.index > len( self.arrs ) - 1:
              raise StopIteration
          else:
              self.index +=1
              return self.arrs[ self.index - 1 ]

#可迭代对象
class OwnIterable( Iterable ):
      def __init__(self ,  arrs ):
          self.arrs = arrs
      def __iter__(self):
          return OwnIteror( self.arrs )

for item in OwnIterable( [ 1,2,3,4,4,6 ] ):
      print item

 

posted @ 2016-10-05 16:19  codefly-sun  阅读(2214)  评论(0编辑  收藏  举报