一.yield的表达式形式
1. 用法:
def ff():
print(‘starting’)
while True:
x = yield
print('x= ', x)
g = ff() # 产生的是生成器
print(next(g)) # 第一次迭代,输出为:x= None None 注:第二个None为yield返回值,可在yield后面写上要返回的值,不影响x的值
print(next(g)) # 迭代一次,输出为:x= None None
print(g.send(2)) #给yield传值2,即x=2,并迭代一次,输出为:x = 2 None 注:g的第一次迭代若要用send迭代,传值必须为None
2. send的效果:
(1)先为暂停位置的那个yield传一个值,然后yield会把值赋给x
(2)与next的功能一样
3. 加装饰器
由于第一次迭代时不需要传值,因此可以写一个装饰器来得到迭代过一次后的生成器
def init(func):
def wrapper(*args,**kwargs):
g = func(*args,**kwargs)
next(g)
return g
return wrapper
二.面向过程编程
1. 根据菜单做菜
@init #引用上面的init装饰器
def eater(name):
print(‘%s is ready to eat’ %name)
food_made_list = []
while True:
food = yield
food_made_list.append(food)
print(‘%s is OK’ %food_made_list)
def make_food(target,food_list):
for food in food_list:
target.send(food) #将food_list中的元素作为参数传入target函数,同时使target迭代一次
make_food(eater('tom'),['banana','watermelon'] )
2. 改进
@init #引用上面的init装饰器
def eater(name):
print(‘%s is ready to eat’ %name)
food_made_list = []
while True:
food = yield
food_made_list.append(food)
print(‘%s is OK’ %food_made_list)
@init
def make_food(target):
while True:
food_list = yield
for food in food_list:
target.send(food) #将food_list中的元素作为参数传入target函数,同时使target迭代一次
g = make_food(eater('tom'))
g.send(['banana','watermelon']) #将food_list作为参数传入,并使make_food迭代一次