如下
# __author__ = liukun # coding:utf-8 def it(): print ('hello') yield 1 yield 1 a= it() print("#############") print(a) print("*************") for i in a: print (i)
结果:
/Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 /Applications/PyCharm.app/Contents/helpers/pycharm/utrunner.py /Users/kamil/PycharmProjects/untitled4/Day5/python基础教程/test.py true Testing started at 下午4:33 ... ############# <generator object it at 0x1016babf8> ************* hello 1 1 Process finished with exit code 0 Empty test suite.
从上面可以看出当执行generator函数的时候仅仅做的是生成了一个特殊的iterator对象,并没有执行里面的内容
再来
a = 1 def it(): global a yield 3 a += 1 yield 4 for i in it(): print ("i=%d;a=%d" %(i,a))
'''
i=3;a=1
i=4;a=2
'''
如果:
a = 1 def it(): global a a += 1 yield 3 yield 4 for i in it(): print ("i=%d;a=%d" %(i,a))
'''
i=3;a=2
i=4;a=2
'''
yield的作用就是,每次发生next()调用,函数执行完yield语句之后在挂起,这时返回yield的值(你愿意yield啥就yield啥),整个函数状态被保存,等待下一次next()调用;下次next()调用发生时,从yield后的语句开始执行(有yiled也在循环体内,未必一定是顺序的),直到再次遇到yield为止,然后重复删除动作