python yield的簡單理解

yield是個生成器,它可使一個方法變成可迭代的方法,每次迭代返回yield後面的值python

簡單理解:shell

>>>def t1():
	 yield 1
	 yield 2
	 yield 3


>>> t = t1();
>>> t.__next__()
1
>>> t.__next__()
2
>>> t.__next__()
3

#又或者
>>> for v in t1():
	print(v)

1
2
3
#注意:t1().__next__()這隻會永遠都返回1,由於每次都迭代了這個方法的不一樣實例
>>> t1().__next__()
1
>>> t1().__next__()
1
>>> t1().__next__()
1
>>>

從上面能夠看出實例化這個方法後,每次調用他的__next__()方法都返回yield後面的值code

進一步three

>>> def t2():
	  yield 1
	  print('hello1')
	  yield 2
	  print('hello2')
	  yield 3
	  print('hello3')

	
>>> t = t2()
>>> t.__next__()
1
>>> t.__next__()
hello1
2
>>> t.__next__()
hello2
3
>>> t.__next__()
hello3
Traceback (most recent call last):
  File "<pyshell#72>", line 1, in <module>
    t.__next__()
StopIteration
>>>

第一次執行next方法後,該方法只運行到 第一個yield後次方法就暫停執行了,直到再次調用該實例的next方法纔會繼續往下執行直到遇到下一個yield,該實例調用到第四次next方法後會繼續往下執行,同時會拋出一個異常,表示該方法已經迭代完成了generator

對於send方法的理解:io

>>> def t3():
	   m = yield 1
	   print('send1 value is ',m)
	   n = yield 2
	   print('send2 value is ',n)
	   k = yield 3
	   print('send2 value is ',k)

	
>>> t = t3()
>>> t.send('one')#t.send(None)則不會報異常
Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    t.send('one')
TypeError: can't send non-None value to a just-started generator
>>> t.__next__()
1
>>> t.send('one')
send1 value is  one
2
>>> t.__next__()# 返回None
send2 value is  None
3
>>> t.send('three')
send2 value is  three
Traceback (most recent call last):
  File "<pyshell#90>", line 1, in <module>
    t.send('three')
StopIteration

send方法是給yield 一個返回值,但在沒作迭代直接調用send方法會報異常,每調用一次send方法至關於進行了一次迭代。若是經過調用next方法進行迭代,那麼yield返回的是Noneast

相關文章
相關標籤/搜索