NewsDog Python开发工程师面试题

匿名网友 匿名网友 发布于: 2016-11-25 00:00:00
阅读 171 收藏 0 点赞 0 评论 0

实现一个可迭代的类

class MyClass(object):

def __init__(self, n):

self.idx = 0

self.n = n

 

def __iter__(self):

return self

 

def next(self):

if self.idx < self.n:

val = self.idx

self.idx += 1

return val

else:

raise StopIteration

其实,可以作用于for循环的对象都是可迭代对象(Iterable),for循环就是使用next()函数实现的,但是next()函数中的参数必须是

迭代器(Iterator),对于list,tuple,dict,str等类型是可迭代的,却不是迭代器,它们的for循环实现是先用了iter()函数获得一个

Iterator对象。

迭代器是一个惰性计算序列,不断调用next()函数才计算下一个结果,并直到结尾时返回StopIteration异常。迭代器对象必须实现__iter__()和

next()方法。

评论列表
文章目录