Build a Basic Python Iterator

前端 未结 10 1243
南旧
南旧 2020-11-21 12:22

How would one create an iterative function (or iterator object) in python?

10条回答
  •  庸人自扰
    2020-11-21 12:47

    I see some of you doing return self in __iter__. I just wanted to note that __iter__ itself can be a generator (thus removing the need for __next__ and raising StopIteration exceptions)

    class range:
      def __init__(self,a,b):
        self.a = a
        self.b = b
      def __iter__(self):
        i = self.a
        while i < self.b:
          yield i
          i+=1
    

    Of course here one might as well directly make a generator, but for more complex classes it can be useful.

提交回复
热议问题