生成器

# 什么是生成器?只要在函数内部出现yield的关键字,那么再执行函数时,就不会执行函数体代码,会得到一个结果,该结果就是生成器
# def func():
# print('>>:1')
# yield 1
# print('>>:2')
# yield 2
# print('>>:3')
# yield 3
#
# g=func()
# print(g) # <generator object func at 0x000001FE953A8DC8>
# g.__next__()
# g.__iter__()
# 生成器就是迭代器
# res1=next(g) # >>:1
# print(res1) # 1
# res2=next(g) # >>:2
# print(res2) # 2
# res3=next(g) # >>:3
# print(res3) # 3

# yield的功能:
# 为我们提供了一种自定义迭代器对象的方法
# yield与return的区别在于yield可以返回多次值,函数暂停与再继续的状态是由yield帮忙保存的

# obj=range(1,100000000000000000000000000000000000,9527)
# print(obj) # range(1, 100000000000000000000000000000000000, 9527)

# range得到的是一个可迭代对象
# obj_iter=obj.__iter__()
# print(next(obj_iter)) # 1
# print(next(obj_iter)) # 9528
# print(next(obj_iter)) # 19055

# def my_range(start,stop,step=1):
# while start < stop:
# yield start
#
# g=my_range(1,6,2)
# print(next(g)) # 1
# print(next(g)) # 1
# print(next(g)) # 1

# def my_range(start,stop,step=1):
# while start < stop:
# yield start
# start += step
#
# g=my_range(1,6,2)
# print(next(g)) # 1
# print(next(g)) # 3
# print(next(g)) # 5]

# tail -f access.log/grep'404'
# import time
# def tail(filepath):
# with open(filepath,'rb')as f:
# f.seek(0,2)
# while True:
# line=f.readline()
# if line:
# yield line
# else:
# time.sleep(0.05)
#
# lines=tail('a.txt')
# # print(lines) # <generator object tail at 0x0000028E6A7A0448>
# def grep(lines,pattern):
# for line in lines:
# line=line.decode('utf-8')
# if pattern in line:
# print(line)
#
# grep(lines,'404')
#
# def grep(lines,pattern):
# for line in lines:
# line=line.decode('utf-8')
# if pattern in line:
# yield line
#
# g=grep(tail('a.txt'),'404')
# print(g)
#
# for line in lines:
# print(line)

# 了解知识点:
# yield表达式形式的用法
# def eater(name):
# print('%s start eat'%name)
# while True:
# food=yield
# print('%s start eat %s'%(name,food))
#
# e=eater('Alice')
# # 首先初始化
# next(e) # Alice start eat
# # 然后e.send 1、从暂停的位置,将值传给yield;2、与next一样
# e.send('blueberry') # Alice start eat blueberry
# e.send('Mulberry') # Alice start eat Mulberry
# e.send('Apple') # Alice start eat Apple

# def eater(name):
# print('%s start eat'%name)
# food_list=[]
# while True:
# food=yield food_list
# food_list.append(food)
# print('%s start eat %s'%(name,food))
#
# e=eater('Alice')
# print(e.send(None))
# print(e.send('blueberry'))
# print(e.send('Mulberry'))
# print(e.send('Apple'))
'''
Alice start eat
[]
Alice start eat blueberry
['blueberry']
Alice start eat Mulberry
['blueberry', 'Mulberry']
Alice start eat Apple
['blueberry', 'Mulberry', 'Apple']
'''
原文地址:https://www.cnblogs.com/0B0S/p/11991766.html