class MyRange: def __init__(self, end=3): self.start = 0 self.end = end def __iter__(self): return self def __next__(self): if self.start < self.end: ret = self.start self.start += 1 return ret else: raise StopIteration t = MyRange() for i in t: print(i) ## 运行结果: 0 1 2
对于test这个类来说,它定义了__iter__和__next__函数,所以是一个可迭代的类,也可以说是一个可迭代的对象