除了可以使用 next() 方法来获取下一个生成的值,用户还可以使用 send() 方法将一个新的或者是被修改的值返回给生成器。除此之外,还可以使用 close() 方法来随时退出生成器。
EXAMPLE 3:
In [5]: def counter(start_at=0):
...: count = start_at
...: while True:
...: val = (yield count)
...: if val is not None:
...: count = val
...: else:
...: count += 1
...:
In [6]: count = counter(5)
In [7]: type(count)
Out[7]: generator
In [8]: count.next()
Out[8]: 5
In [9]: count.next()
Out[9]: 6
In [10]: count.send(9) # 返回一个新的值给生成器中的 yield count
Out[10]: 9
In [11]: count.next()
Out[11]: 10
In [12]: count.close() # 关闭一个生成器
In [13]: count.next()
---------------------------------------------------------------------------
StopIteration Traceback (most recent call last)
<ipython-input-13-3963aa0a181a> in <module>()
----> 1 count.next()
通过改进查找文件中最长的行的功能实现来看看生成器的优势。
EXAMPLE 4 : 一个比较通常的方法,通过循环将更长的行赋值给变量 longest 。
f = open('FILENAME', 'r')
longest = 0
while True:
linelen = len(f.readline().strip())
if not linelen:
break
if linelen > longest:
longest = linelen
f.close()
f = open('FILENAME', 'r')
longest = 0
allLines = f.readlines()
f.close()
for line in allLines:
linelen = len(line.strip())
if not linelen:
break
if linelen > longest:
longest = linelen
f = open('FILENAME', 'r')
longest = 0
allLines = [x.strip() for x in f.readlines()]
f.close()
for line in allLines:
linelen = len(line)
if not linelen:
break
if linelen > longest:
longest = linelen