高级农民
- 积分
- 1466
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-4
- 最后登录
- 1970-1-1
|
本帖最后由 sky420 于 2015-6-15 05:24 编辑
Berkely的CS61A,倒数第二周的视频,可以去我的网页查,gaotx.com/cs61a。不清楚其他的语言,在上cs61a,主要用python, 最近正好讲到这个概念。因为术语不知道翻译过来准不准确,所以我用英语简单介绍一下。
Take for loop as an example to specifiy the iterable and iterator. The object that for loop iterates over is required to be iterable.- for elem in iterable: do something
复制代码 What the for loop exactly does is that it uses __iter__ method to get an iterator from the iterable and gets value or element from the iterator using __next__ method. Thus, iteratble must implement iterable interface which contains __iter__ method. It seems that iterator only requires to implement __next__ method, but it is not ture. Actually iterator is also an iterable because after first iteration, in order to make next iteration, for loop needs to call the iterator that is returned from the first iteration to get another iterator using __iter__ method. Then, use the new iterator from the second iteration to get new value by __next__ method. Thus, an iterator needs to implement interator interface which includes both __iter__ and __next__ method. Note that for iterator, __next__ method usually return itself.
class Iterable:
def __init__(self):
do something
def __iter__(self):
do something
class Iterator:
def __init__(self):
self.start = 5
def __next__(self):
do something
def __iter__(self):
return self
|
|