• Python中的iterable和iterator


    参照官方文档:

    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__中返回来查看效果

  • 相关阅读:
    转:选择学习“下一个”程序语言
    再谈 Web 字体的现状与未来
    堪称2008年最漂亮的50组图标(上)
    堪称2008年最漂亮的50组图标(下)
    回帖整理: 互联网的未来, 我们的未来, 算一个预告吧, 有空我会把这些观点一一展开
    [回帖整理]创业建议
    也论PageController/FrontController与MVC
    [回帖整理] 创业难
    是否非要用interface关键字来实现接口?
    又论社区风气, 与程序员是干嘛地的.
  • 原文地址:https://www.cnblogs.com/geeklove01/p/8682489.html
Copyright © 2020-2023  润新知