python 之yield个人理解
2016-07-29 11:01
507 查看
!/usr/bin/python3 #-*- coding:utf-8 -*- def a(max): n = 0 while n < max: c = ['aa','bb','cc','dd','rr','ff'] print 'yield 前面',n yield c print 'yield 后面',n n+=1 for i in a(6): print "for循环print:" ,i print '--' *25执行过程:
通过结果可以看出:首先for循环调用函数,执行函数执行到截止yield的部分代码:
def a(max): n = 0 while n < max: c = ['aa','bb','cc','dd','rr','ff'] print 'yield 前面',n #n为0 yield c #这时n为0执行到yield返回c
这个列表的值,然后继续运行for循环:
for i in a(6): print "for循环print:" ,i print '--' * 25执行完for循环,继续调用函数,这时并不是重新执行函数,而是从刚才yield的截断点开始执行,返回print n的值还没有n+1 所以返回为0!!!
然后继续执行函数,会打印n+1的值,遇到yield继续截断,开始执行for循环---如此反复。
结果:
yield 前面 0 for循环print: aa -------------------------------------------------- yield 后面 0 yield 前面 1 for循环print: bb -------------------------------------------------- yield 后面 1 yield 前面 2 for循环print: cc -------------------------------------------------- yield 后面 2 yield 前面 3 for循环print: dd -------------------------------------------------- yield 后面 3 yield 前面 4 for循环print: rr -------------------------------------------------- yield 后面 4 yield 前面 5 for循环print: ff -------------------------------------------------- yield 后面 5
相关文章推荐
- Python中对于yield的个人理解
- Python Twisted Finger:moving to a component based architecture的个人理解
- python之yield理解
- 深入理解python中的yield
- python yield 实例理解要点
- Python中yield深入理解
- Python天天美味(25) - 深入理解yield
- 深入理解python的yield和generator
- python的self之个人理解
- 【Python笔记】如何理解python中的generator functions和yield表达式
- 【Python注意事项】如何理解python中间generator functions和yield表情
- Python中yield的理解
- 【python】理解迭代器及yield
- python中的__call__的个人理解(wsgi实例解释)
- Python 深入理解yield
- Python 深入理解yield
- 对Python中yield的理解
- Python天天美味(25) - 深入理解yield
- yield个人理解及简明示例
- Python 深入理解yield