---
title: "Python 迭代器 iteraor"
author: "GhostFromheaven"
date: "2012-06-03T13:06:28Z"
tags: []
categories: ["编程语言"]
slug: "python-iteraor"
draft: false
lastmod: "2012-06-03T13:09:44Z"
id: 1547535
url: "https://ghostfromheaven.iteye.com/blog/1547535"
---

**Python迭代器 iterator**

--by [GhostFromHeaven](/)

 

迭代器是一个实现迭代器协议的容器对象，它基于两个方法：

**next** 返回容器的下一个元素；

**\_\_iter\_\_** 返回迭代器本身。

迭代器可以通过内置函数iter和一个序列作为参数创建，如下：

```
>>> i = iter('iter')
>>> i.next()
'i'
>>> i.next()
't'
>>> i.next()
'e'
>>> i.next()
'r'
>>> i.next()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
StopIteration
```

```

```

 

序列遍历完后，继续调用next()就会抛出**StopIteration异常**。

 

要创建自己的迭代器，可以实现迭代器协议，即**实现****next方法和\_\_iter\_\_特殊方法**。

 

```
>>> class MyIterator(object):
...     def __init__(self, step):
...         self.step = step
...     def next(self):
...         """Returns the next element."""
...         if self.step == 0:
...             raise StopIteration
...         self.step -= 1
...         return self.step
...     def __iter__(self):
...         """Returns the iterator itself."""
...         return self
... 
>>> for el in MyIterator(4):
...     print el
... 
3
2
1
0
```