生成器:
在函数内部包含yield关键字,那么该函数执行的结果就是生成器(生成器就是迭代器)
def func(): print('first') yield 1111 print('second') yield 2222 g = func() print(next(g)) print(next(g))
from collections import Iterator
print(isinstance(g,Iterator))#判断g是否是生成器
yield的功能:1.把函数的执行结果做成迭代器(帮函数封装好__iter__,__next__方法)
2.函数暂停与再继续运行的状态是由yield保存的
def func(n): while True: yield n n += 1 g = func(0) print(next(g)) def my_range(start,stop): while True: if start == stop: raise StopIteration else: yield start start += 1 g = my_range(1,3) for i in g: print(i)
yield与return的比较?
相同点:都有返回值的功能
不同点:return只能返回一次值,而yield可以返回多次值
import time def tail(filepath): with open(filepath,'r') as f: f.seek(0,2) while True: line = f.readline() if line: yield line else: time.sleep(0.2) lines = tail('access.log') #管道是传递不同介质之间数据的问题 def grep(pattern,lines): for line in lines: if pattern in lines: print(line,end = '') grep('error',lines)