python yield的简单理解

本文深入浅出地介绍了Python中生成器的概念与应用。通过多个示例详细解释了yield关键字的作用,包括如何使用生成器进行迭代操作及send方法的正确用法。

yield是个生成器,它可以使一个方法变成可迭代的方法,每次迭代返回yield后面的值

简单理解:

>>>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后面的值

进一步

>>> 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方法后会继续往下执行,同时会抛出一个异常,表示该方法已经迭代完成了

对于send方法的理解:

>>> 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返回的是None

转载于:https://my.oschina.net/u/351612/blog/1527681

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值