Python yield语法 使用实战详解
2014-09-08 21:28
771 查看
感谢朋友支持本博客,欢迎共同探讨交流,由于能力和时间有限,错误之处在所难免,欢迎指正! 如有转载,请保留源作者博客信息。 Better Me的博客:blog.csdn.net/tantexian 如需交流,欢迎大家博客留言。 # 例一开始:--------------------------------------------------------------------------------------------------------------------- def test_yield1(): print 'I am make test_yield1 function as a iterator...' yield #直接调用test_yield1() test_yield1() #没有输出结果,原因是执行test_yield1()函数只是构造了一个迭代器, # 相当于只写了个for循环,没有写for循环的代码逻辑 # 迭代方法1: for i in test_yield1(): pass #发现有输出了,这是因为test_yield1函数中有yield字段,因此test_yield1函数变成了一个 # 可迭代的生成器constructor,所以用迭代的方法能使之输出结果。 # 迭代方法2: it = test_yield1() it.next() 迭代方法1、迭代方法2的执行结果都一样: #但是使用下面方式则会报错 it = test_yield1() it.next() it.next() #报错StopIteration,这是因此yield只构造了一次迭代对象,所以执行第二次时候,已经没有可迭代的元素了,所以报错 # 例一结束:--------------------------------------------------------------------------------------------------------------------- |
# 例二开始:--------------------------------------------------------------------------------------------------------------------- #接上面例一,制造一个二次迭代的函数对象: def test_yield2(): print 'I am test_yield2 and execute once yiled...' yield print 'I am test_yield2 and execute twice yiled...' yield #直接执行一样没有输出 test_yield2() # 迭代方法1: for i in test_yield2(): pass # 迭代方法2: t = test_yield2() t.next() t.next() 迭代方法1、迭代方法2的执行结果都一样: # 例二结束:--------------------------------------------------------------------------------------------------------------------- |
下面来看一个openstack中使用的实例编程的例子:
初看不是很好理解,接下来,模拟一个demo:
#coding=utf-8 # 例三开始:--------------------------------------------------------------------------------------------------------------------- def test_yield3(num_list): for num in num_list: if num%2 == 0: yield num num_list = [1,2,3,4,5,6] t = test_yield3(num_list) print t for i in t: print i 结果: # 例三结束:--------------------------------------------------------------------------------------------------------------------- |
就是将self._filter_one(obj, filter_properties)值为true的obj加入到迭代对象中。这样就完成了对hosts的过滤。
相关文章推荐
- Python yield语法 使用实战详解
- Python yield 使用浅析,关于generator的详解
- python的协程和并发-使用yield实现并有使用详解
- Python 3中的yield from语法详解
- python之sqlite3使用详解
- VMSTAT的语法详解及使用
- python编辑器——wingIDE的使用详解
- Python连载系列之Python语法基础1:开始使用Python
- 详解Java的JDBC API的存储过程与SQL转义语法的使用
- python的logging.config使用详解
- Python特殊语法:filter、map、reduce、lambda、yield
- “Oracle大型数据库系统在AIXUNIX上的实战详解” 答疑十三:使用大文件表空间
- python的logging.config使用详解
- 【 Makefile 编程基础之四】详解Makefile 函数的语法与使用(中)
- 【 Makefile 编程基础之四】详解Makefile 函数的语法与使用(下)
- python的yield语法基础
- 【 Makefile 编程基础之四】详解Makefile 函数的语法与使用!
- python之sqlite3使用详解
- python语法31[iterator和generator+yield]
- python之sqlite3使用详解