📣 黑五价提前开抢|VIP一年通行证5折,蓝莓、Offer多多同步特惠
12
返回列表 发新帖
楼主: AveMaleficum
跳转到指定楼层
上一主题 下一主题
收起左侧

哪门公开课讲了Iterator的概念啊?

🔗
wilbur_zzz 2015-4-6 15:09:26 | 只看该作者
全局:
Iterator其实没什么难理解的,我当时也不知道是啥,其实很简单,地基那楼说的挺好
回复

使用道具 举报

🔗
sky420 2015-6-15 04:36:29 | 只看该作者
全局:
本帖最后由 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.
  1. 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


回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表