day13生成器
# 生成器 —— 迭代器
# 生成器函数 —— 本质上就是我们自己写得函数
# 生成器表达式
#普通函数
# def generator():
# print(1)
# return 'a'
# ret = generator()
# print(ret)
#生成器函数:只要含有yield关键字的函数都是生成器函数
#yield不能和return共用且需要写在函数内部
def generator1():
print(1)
yield 'a'
#生成器函数:执行之后会得到一个生成器作为返回值
ret1 = generator1()
print(ret1)
print(ret1.__iter__())
print(ret1.__next__())
def generator():
print(1)
yield 'a'
print(2)
yield 'b'
yield 'c'
g = generator()
ret = g.__next__()
print(ret)
ret = g.__next__()
print(ret)
ret = g.__next__()
print(ret)
#或者使用for循环
for i in g:
print(i)
#娃哈哈%i
def wahaha():
for i in range(2000000):
yield '娃哈哈%s'%i
g = wahaha()
g1 = wahaha()
print(g.__next__())
print(g1.__next__())
g = wahaha()
count = 0
for i in g:
count +=1
print(i)
if count > 50:
break
# print('*******',g.__next__())
for i in g:
count +=1
print(i)
if count > 100:
break
#监听文件例子
def tail(filename):
f = open(filename,encoding='utf-8')
while True:
line = f.readline()
if line.strip():
yield line.strip()
g = tail('file')
for i in g:
if 'python' in i:
print('***',i)