码迷,mamicode.com
首页 > 编程语言 > 详细

Python__协成函数part1

时间:2017-07-30 01:01:32      阅读:456      评论:0      收藏:0      [点我收藏+]

标签:alt   返回   pre   返回值   app   isp   opened   strip()   str   

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

标签:alt   返回   pre   返回值   app   isp   opened   strip()   str   

原文地址:http://www.cnblogs.com/wangmengzhu/p/7257989.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!