1. 简介
string, list, tuple等都是常见的迭代器类型的数据类型。我们自己也可以创建迭代器类型的class,从而可以用for-in遍历对象中的各个元素。
2. 概念
-
以下摘自python27.chm:
-
iterable
- A container object capable of returning its members one at a time. Examples of iterables include all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed ( zip(), map(), ...). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object. This iterator is good for one pass over the set of values. When using iterables, it is usually not necessary to call iter() or deal with iterator objects yourself. The for statement does that automatically for you, creating a temporary unnamed variable to hold the iterator for the duration of the loop. See also iterator, sequence, and generator. iterator
-
An object representing a stream of data. Repeated calls to the iterator’snext() method return successive items in the stream. When no more data are available aStopIteration exception is raised instead. At this point, the iterator object is exhausted and any further calls to itsnext() method just raiseStopIteration again. Iterators are required to have an__iter__() method that returns the iterator object itself so every iterator is also iterable and may be used in most places where other iterables are accepted. One notable exception is code which attempts multiple iteration passes. A container object (such as a list) produces a fresh new iterator each time you pass it to theiter() function or use it in afor loop. Attempting this with an iterator will just return the same exhausted iterator object used in the previous iteration pass, making it appear like an empty container.
More information can be found in Iterator Types.
3. 示例代码
import math
def is_prime(n):
if n < 2:
return False
end_number = int(math.sqrt(n)) + 1
for i in range(2, end_number):
if n % i == 0:
return False
return True
class Prime(object):
def __init__(self, stop=None):
if stop is not None:
self.stop = stop
else:
self.stop = -1
self.curIndex = 1
def __iter__(self):
return self
def is_end(self):
return self.stop != -1 and self.curIndex >= self.stop
def next(self):
n = None
while n is None:
if Prime.is_end(self):
raise StopIteration
if is_prime(self.curIndex):
n = self.curIndex
self.curIndex += 1
return n
def _test():
prime = Prime(100)
for item in prime:
print item,
print
def _test_prime():
values = [2, 3, 5, 15]
for value in values:
print value,
print is_prime(value)
print
if __name__ == '__main__':
_test_prime()
_test()
4. 运行结果
D:\examples\python\iterable>prime.py
2 True
3 True
5 True
15 False
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97
D:\examples\python\iterable>