码迷,mamicode.com
首页 > 编程语言 > 详细

Python中的iterable和iterator

时间:2018-04-01 21:52:03      阅读:196      评论:0      收藏:0      [点我收藏+]

标签:seq   item   生成器   ext   pre   pytho   sed   成员   ret   

参照官方文档:

1 iterable是一个能返回它的成员的对象。包括sequence types(list,str,tuple) and not-sequence types(dict, file objects), objects and classed defined with an __iter__() method or a __getitem__() method 

当一个iterable object传入 iter()方法(同样是调用__iter__()方法的时候)的时候,会返回一个iterator. 这是显式创建iterator的方法。当我们用for遍历的时候,iterator会自动创建iterator

2 iterator应该定义一个__iter__()方法(或者一个供迭代的生成器),由于有这个方法都是iterable的,所以iterator都是iterable的

iterator的__iter__()方法返回的是iterator object itself

为什么iterator都是iterable的?因为iterator(比如list)都是可以重复遍历的(想象并发情况下),所以需要每次__iter__()的时候返回一个独立的迭代器。

如果iterator不是iterable的,那么每次调用都只返回同一个iterator,一旦这个iterator到达了StopIteration的条件,就完了

注:用for遍历对象的时候,如果对象没有__iter__,但是实现了__getitem__,会使用下标迭代的方式

      iter也是一样,当__iter__方法没有的时候,返回一个用下标迭代的可迭代对象来代替,比如str 

可以用一个例子来解释这一切:

class B(object):
    def __init__(self):
        pass

def next(self): yield in B next class A(object): def __init__(self): self.b = B() def next(self): print in A next def __iter__(self): return self.b a = A() for a_next in a: # 迭代的时候,a_next指向的是 B.next for a_next_value in a_next: # 使用for遍历生成器B.next,由于B.next是无状态的,所以可以一直死循环yield print a_next_value

可以把B.next中的内容改写成return ‘in B next‘,将A.__iter__改为yield ‘in A iter‘, return ‘in A iter‘,甚至在B中再定义一个生成器函数在A.__iter__中返回来查看效果

Python中的iterable和iterator

标签:seq   item   生成器   ext   pre   pytho   sed   成员   ret   

原文地址:https://www.cnblogs.com/geeklove01/p/8682489.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!