标签:一个 生成器 top ISE 无法获得 generate __next__ stop pre
def use_range(): """python内置range函数""" for i in range(5, 10): print(i) class IterateRange(object): """使用迭代器模拟range函数""" def __init__(self, start, end): self.start = start - 1 # 因为在__next__方法中,一开始就加1了,如果不先减,那么就无法获得它自身的第一个数 self.end = end def __next__(self): self.start += 1 if self.start >= self.end: raise StopIteration return self.start def __iter__(self): return self class GenRange(object): """使用生成器来模拟range函数""" def __init__(self, start, end): self.start = start - 1 self.end = end def get_num(self): while True: if self.start >= self.end - 1: break self.start += 1 yield self.start def get_num(start, end): start -= 1 while True: if start >= end - 1: break start += 1 yield start if __name__ == "__main__": use_range() # 输出5-9的数 iterate = IterateRange(5, 10) for i in iterate: print(i) generate = GenRange(5, 10).get_num() for i in generate: print(i) num = get_num(5, 10) for i in num: print(i)
【Python面向对象】(12)用生成器和迭代器模拟range函数
标签:一个 生成器 top ISE 无法获得 generate __next__ stop pre
原文地址:https://www.cnblogs.com/ac-chang/p/12751967.html