迭代器的简单理解:
iter()
__iter__()
next()
__next__()
例如构造简单的阶乘:
class factorial:
def __init__(self,n):
self.sum =1
self.end = n
self.start = 1
def __iter__(self):
return self
def next(self):
if self.start <= self.end:
self.sum *= self.start
self.start +=1
return self.sum
else:
raise StopIteration
f1 = factorial(4)
#方式1
it = iter(f1)
print it.next()
print it.next()
print it.next()
print it.next()
#方式2
for each in f1:
print each
it.next()会让迭代指针一直指向下个目标,所以执行4次it.next()后,在再执行for语句,则无任何输出