标签:
By now, you‘ve probably noticed that most container objects can looped over using a for
statement:
现在你可能注意到大多数容器对象都可以用 for
遍历:
for element in [1, 2, 3]: print element for element in (1, 2, 3): print element for key in {‘one‘:1, ‘two‘:2}: print key for char in "123": print char for line in open("myfile.txt"): print line
This style of access is clear, concise, and convenient. The use of iterators pervades and unifies Python. Behind the scenes, the for
statement calls iter() on the container object. The function returns an iterator object that defines the method next() which accesses elements in the container one at a time. When there are no more elements, next() raises a StopIteration exception which tells the for
loop to terminate. This example shows how it all works:
这种形式的访问清晰、简洁、方便。这种迭代器的用法在 Python 中普遍而且统一。在后台,for
语句在容器对象中调用 iter() 。 该函数返回一个定义了 next() 方法的迭代器对象,它在容器中逐一访问元素。没有后续的元素时,next() 抛出一个 StopIteration 异常通知 for
语句循环结束。以下是其工作原理的示例:
>>> s = ‘abc‘ >>> it = iter(s) >>> it >>> it.next() ‘a‘ >>> it.next() ‘b‘ >>> it.next() ‘c‘ >>> it.next() Traceback (most recent call last): File "", line 1, in -toplevel- it.next() StopIteration
Having seen the mechanics behind the iterator protocol, it is easy to add iterator behavior to your classes. Define a __iter__() method which returns an object with a next() method. If the class defines next(), then __iter__() can just return self
:
了解了迭代器协议的后台机制,就可以很容易的给自己的类添加迭代器行为。定义一个 __iter__() 方法,使其返回一个带有 next() 方法的对象。如果这个类已经定义了 next(),那么 __iter__() 只需要返回self:
>>> class Reverse: "Iterator for looping over a sequence backwards" 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] >>> for char in Reverse(‘spam‘): print char
标签:
原文地址:http://my.oschina.net/yangting880815/blog/464967