2019-03-15
阅读量:
843
Python中的iterable的工作机制?
拿一个例子看看,首先定义一个有__iter__方法,但是没有next()方法的类 (PS:在python2中是next(),python3是__next__()):
from collections import Iterable, Iterator
class Student(object):
def __init__(self,score):
self.score=score
def __iter__(self):
return iter(self.score)
test= Student([80,90,95])
print isinstance(test, Iterable)
print isinstance(test, Iterator)
for i in test:
print i
##result
True
False
80
90
95
##可重复遍历
for i in test:
print i
##result
80
90
95
上面代码的结果印证了定义中提到的:
缺少了next()方法,可迭代对象就不是迭代器。
此外,注意到:可迭代对象通过__iter__方法每次都返回了一个独立的迭代器,这样就可以保证不同的迭代过程不会互相影响。






评论(0)


暂无数据
推荐帖子
2条评论
6条评论
7条评论