【问题标题】:Python: Understanding yield assignment in generatorPython:理解生成器中的产量分配
【发布时间】: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**

这是一个正确的理论吗?有关其工作原理的更多详细信息?

【问题讨论】:

    标签: python generator yield


    【解决方案1】:

    但是随后,即使message = yield objects[count] 已经被执行,message 的值也会从None 更改为10

    没有。已产生一个值,但在调用send 之前,yield objects[count] 表达式的值尚未确定或分配给message。生成器的执行在执行该行的中途暂停。 (请记住,yield 表达式的值与其产生的值不同。)

    x.send(10) 调用导致yield 表达式取值10,而该值是分配给message 的值。

    【讨论】:

    • 太棒了,这就是我错过的部分。
    猜你喜欢
    • 2019-04-10
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 2017-12-27
    • 2015-11-14
    • 2021-07-27
    • 2020-06-10
    • 2011-01-01
    相关资源
    最近更新 更多