实现了__iter__方法的类的实例是可迭代对象,实现了__next__方法的类的实例是迭代器对象,实现了__getitem__方法的类的实例是可切片对象(支持a[begin :end :step]操作)。下面的例子展示了常用的设计模式——迭代器模式的Python实现。
from collections.abc import Iterator
class Company:
def __init__(self, name, empolyees):
self.name = name
self.employee_list = list(empolyees)
def __iter__(self):
return CompanyIterator(self.employee_list)
class CompanyIterator(Iterator):
def __init__(self, employee_list):
self._iter_list = employee_list
self._index = 0
def __next__(self):
try:
item = self._iter_list[self._index]
except IndexError:
raise StopIteration
self._index += 1
return item
if __name__ == '__main__':
company = Company('HIT', ('Obuy', 'Euy', 'Naij'))
for employee in company:
print(employee)
执行结果
Obuy
Euy
Naij
当一个函数中出现包含yield关键字的语句时,该函数就会被Python解释器解释为一个生成器对象。下面用一个求解斐波那契数列的例子说明生成器的用法。
def Fib(index):
"""
yield first #index elements in Fibonacci Array
"""
n, a, b = 0, 0, 1
while n < index:
yield b
a, b = b, a+b
n += 1
if __name__ == '__main__':
for item in Fib(10):
print(item)
执行结果
1
1
2
3
5
8
13
21
34
55