首页 > 代码库 > Python__协成函数part1

Python__协成函数part1

yield的功能:

    1:把函数的执行结果封装好__iter__和__next__,即得到一个迭代器

    2:与return功能类似,都可以返回值,但不同的是,return只能返回一次值,而yield可以返回多次值

    3:函数暂停与再继续的状态是由yield保存的

技术分享
 1 def init(func):
 2     def wrapper(*args,**kwargs):
 3         g = func(*args,**kwargs)
 4         next(g)
 5         return g
 6     return wrapper
 7 
 8 
 9 @init
10 def eater(name):
11     print(%s start to eat%(name))
12     food_list = []
13     while True:
14         food = yield food_list
15         food_list.append(food)
16         print(%s eat %s%(name,food))
17 g = eater(alex)
18 print(g.send(骨头))
19 
20 @init
21 def func():
22     print(我开动啦!)
23     while True:
24         food = input(>>: ).strip()
25         print(g.send(food))
26 
27 func()
View Code

 

Python__协成函数part1