[Python基础知识]

来源:互联网 发布:js原型链是啥 编辑:程序博客网 时间:2024/06/15 05:36

在Python学习中我们经常看到这三个词,但是总是无法精准的定义它们的含义,以下是我从网上和文档中总结的定义:

iteration

iteration(迭代) 是在一行元素中一次取一个元素的过程

iterator

iterator 是一个可迭代对象,它具有 next() (Python2)或 __next__() (Python3)方法。

在Python3中,当没有更多的元素时,__next __() 引发一个StopIteration异常,它告诉for循环终止。

>>> s = 'abc'>>> it = iter(s)>>> it<iterator object at 0x00A1DB50>>>> next(it)'a'>>> next(it)'b'>>> next(it)'c'>>> next(it)Traceback (most recent call last):  File "<stdin>", line 1, in <module>    next(it)StopIteration

iterable

iterable 是一个迭代器对象,它具有 __iter__() 方法并返回一个iterator ,或具有__getitem__()方法并可以从零开始的顺序索引(并且当索引不再有效时引发IndexError)。

Python里有大量内置的 iterable 类型,如 str、list、tuple、dict、file、range等

In [1]: s = 'abc'In [2]: s.__iter__()Out[2]: <str_iterator at 0x2200bc10f28>In [3]: l = ['a', 'b', 'c']In [4]: l.__iter__()Out[4]: <list_iterator at 0x2200bc101d0>In [5]: t = ('a', 'b', 'c')In [6]: t.__iter__()Out[6]: <tuple_iterator at 0x2200bbd0710>In [7]: d = {'a':1, 'b':2, 'c':3}In [8]: d.__iter__()Out[8]: <dict_keyiterator at 0x2200bb1d0e8>...

举例

看到了迭代器协议背后的机制,很容易将迭代器行为添加到类中。定义一个 __iter__()方法返回对象的__next__() 方法。如果类定义了__next__(),那么__iter__()可以仅仅返回self:

class Reverse:    """迭代器逆序循环一个序列。"""    def __init__(self, data):        self.data = data        self.index = len(data)    def __iter__(self):        return self    def __next__(self):        if self.index == 0:            raise StopIteration        self.index = self.index - 1        return self.data[self.index]
>>> rev = Reverse('spam')>>> iter(rev)<__main__.Reverse object at 0x00A1DB50>>>> for char in rev:...     print(char)...maps

附录

参考资料:

  1. iterators section of the tutorial:

    https://docs.python.org/3/tutorial/classes.html#iterators

  2. iterator types section of the standard types page

    https://docs.python.org/dev/library/stdtypes.html#iterator-types

  3. iterators section of the Functional Programming HOWTO

    https://docs.python.org/dev/howto/functional.html#iterators

原创粉丝点击