美文网首页
python迭代器

python迭代器

作者: DD丿 | 来源:发表于2023-12-12 10:02 被阅读0次

class MyRange:

      def __init__(self, start, end):

             self.value = start

            self.end = end

     def __iter__(self):

            return self

     def __next__(self):

#若当前值大于最后值,捕获 StopIteration  异常

             if self.value >= self.end:

                              raise StopIteration 

             current = self.value

             self.value += 1

             return current

for num in MyRange(1,4):

         print(num)

相关文章

网友评论

      本文标题:python迭代器

      本文链接:https://www.haomeiwen.com/subject/cbrvgdtx.html