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

相关文章
相关标签/搜索