先講結論:
Iterator 是透過一個class 內部宣告__iter__
還有__next__
(python2 是next
)方法來達成可迭代(iterable)的物件(class)
Genetator 是透過yield簡單產生一個iterator的方法(method)
這是一般的iterator
class iterator(object):
def __init__(self, start, stop):
self.start = start
self.stop = stop
def __iter__(self):
return self
def __next__(self):
if self.start >= self.stop:
raise StopIteration
current = self.start**2
self.start += 1
return current
這是用generator產生的方法
def generator(start,end):
for i in range(start,end):
yield i**2
官方document這樣形容generators
Generators are a simple and powerful tool for creating iterators
Anything that can be done with generators can also be done with class-based iterators as described in the previous section. What makes generators so compact is that the __iter__()
and __next__()
methods are created automatically.
之後用法大致上都相同,都具備有iterable的特性,雖然在用list()
的時候感覺很像,是因為list有iterable的特性,但是iterator是用完就丟的概念,不能重複提取,好處是在處理時可以不用佔用到記憶體空間,像python2中xrange的用法