在介绍迭代器之前还有一种iterable对象需要简单的说明。对于iterator和iterable是两个不同的概念。
__getitem__ 的一个对象,当你想实现一个iterable对象的时候,通过实现__iter__方法返回一个iterator而不是iterable。检查一个对象是不是iterable对象一般是通过catch异常的方式去检查,虽然这个方式有点挫;另外一种是检查是否是容器类中的Itreaable对象if isinstance(e, collections.Iterable)。对于一个iterable的对象可以通过调用iter方法返回一个iterator对象,然后进行for loop访问。class Iterable_: def __iter__(self): return iter([1, 2, 3]) it = iter((Iterable_())) for i in it: print "iterable:" + str(i) #输出 iterable:1 iterable:2 iterable:3
class Iterator_: def __init__(self, s, e): self.current = s self.end = e def __iter__(self): return self def next(self): if self.current < self.end: self.index = self.current self.current += 1 return self.index else: raise StopIteration it = Iterator_(5, 8) for i in it: print "iterator:" + str(i) #never print for i in it: print "second iterator:" + str(i) #print again it = Iterator_(5, 8) for i in it: print "second iterator:" + str(i) #输出 iterator:5 iterator:6 iterator:7 second iterator:5 second iterator:6 second iterator:7
print "generator" #first way my_generator = (x for x in range(3)) for i in my_generator: print i #second way def Generator_(l): n = 0 size = len(l) while n < size: yield l[n] n += 1 ge = Generator_([1, 2, 3]) for g in ge: print "generator:" + str(g)