【发布时间】:2017-08-22 16:48:03
【问题描述】:
这是一个无限循环器,我添加了行号打印以方便跟踪程序执行。
def infinite_looper(objects):
count = 0
print("row 35")
while True:
print("row 37")
if count >= len(objects):
count = 0
print("Row 40")
message = yield objects[count]
print("row 42")
print("The message is "+str(message))
print("row 44")
if message != None:
count = 0 if message < 0 else message
print("row 47, count = "+str(count))
else:
count += 1
print("row 50")
print("Row 51")
x = infinite_looper("abcdefghijkl")
print("executing next 1st time")
print(next(x))
print("executing next 2nd time")
print(next(x))
print("executing send 1st time")
print(x.send(10))
输出是:
executing next 1st time
row 35
row 37
Row 40
a
executing next 2nd time
row 42
The message is None
row 44
row 50
Row 51
row 37
Row 40
b
executing send 1st time
row 42
The message is 10
row 44
row 47, count = 10
Row 51
row 37
Row 40
k
我不明白在打印"executing send 1st time" 之前会发生什么。 b 刚刚被程序输出,大概是通过infinite_looper 中的message = yield objects[count] 行。但是随后,即使message = yield objects[count] 已经被执行,message 的值也会从None 更改为10!我唯一的理论是,yield 关键字的工作方式是在执行后执行“停留”在其行上,并且循环器的 send 语句可以使同一行(在本例中为 message = yield objects[count])执行再次。否则,我们会:
executing send 1st time
row 42
The message is **None**
这是一个正确的理论吗?有关其工作原理的更多详细信息?
【问题讨论】: