python3 生成器的send_Python 3:生成器的send方法

我无法理解send方法。我知道它是用来操作发电机的。但是

语法如下:generator.send(value)。

我不知怎么搞不懂为什么值应该成为当前yield表达式的结果。我准备了一个例子:def gen():

for i in range(10):

X = yield i

if X == 'stop':

break

print("Inside the function " + str(X))

m = gen()

print("1 Outside the function " + str(next(m)) + '\n')

print("2 Outside the function " + str(next(m)) + '\n')

print("3 Outside the function " + str(next(m)) + '\n')

print("4 Outside the function " + str(next(m)) + '\n')

print('\n')

print("Outside the function " + str(m.send(None)) + '\n') # Start generator

print("Outside the function " + str(m.send(77)) + '\n')

print("Outside the function " + str(m.send(88)) + '\n')

#print("Outside the function " + str(m.send('stop')) + '\n')

print("Outside the function " + str(m.send(99)) + '\n')

print("Outside the function " + str(m.send(None)) + '\n')

结果是:1 Outside the function 0

Inside the function None

2 Outside the function 1

Inside the function None

3 Outside the function 2

Inside the function None

4 Outside the function 3

Inside the function None

Outside the function 4

Inside the function 77

Outside the function 5

Inside the function 88

Outside the function 6

Inside the function 99

Outside the function 7

Inside the function None

Outside the function 8

坦白地说,这让我很吃惊。在文档中,我们可以看到当执行yield语句时,生成器的状态被冻结,并且expression_list的值返回给next的调用方。

嗯,好像没发生过。为什么我们可以在gen()内部执行if语句和print函数。

我如何理解函数内部和外部的X为什么不同?

好 啊。假设send(77)将77传输到m。好吧,yield表达式变成77。

那么什么是X = yield i?函数内部的77在外部发生时如何转换为5?

为什么第一个结果字符串没有反映生成器中发生的任何事情?

不管怎样,你能对这些send和yield语句做些评论吗?

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值