【问题标题】:what does yield as assignment do? myVar = (yield)yield as assignment 有什么作用? myVar = (产量)
【发布时间】:2023-04-08 07:39:01
【问题描述】:

感谢this question,我很熟悉收益返回值

但是当它在赋值的右边时,yield 会做什么呢?

@coroutine
def protocol(target=None):
   while True:
       c = (yield)

def coroutine(func):
    def start(*args,**kwargs):
        cr = func(*args,**kwargs)
        cr.next()
        return cr 
    return start

我在this blog 的代码示例中发现了这一点,同时研究了状态机和协程。

【问题讨论】:

    标签: python yield


    【解决方案1】:
    • yield 根据生成器函数中定义的逻辑返回数据流。
    • 但是,send(val) 是一种从生成器函数外部传递所需值的方法。

    p.next() 在 python3 中不起作用,next(p) 对 python 2,3 都有效(内置)

    p.next() 不适用于 python 3,出现以下错误,但它仍然适用于 python 2。

    Error: 'generator' object has no attribute 'next'
    

    这是一个演示:

    def fun(li):
      if len(li):
        val = yield len(li)
        print(val)
        yield None
        
    
    g = fun([1,2,3,4,5,6])
    next(g) # len(li) i.e. 6 is assigned to val
    g.send(8) #  8 is assigned to val
    
    

    【讨论】:

      【解决方案2】:

      函数中使用的yield 语句将该函数转换为“生成器”(创建迭代器的函数)。生成的迭代器通常通过调用next() 来恢复。但是,可以通过调用方法 send() 而不是 next() 来将值发送到函数来恢复它:

      cr.send(1)
      

      在您的示例中,这会将值 1 分配给 c 每次。

      cr.next() 等效于cr.send(None)

      【讨论】:

      • 请注意,在能够在生成器上调用 send() 之前,您必须调用 next() 才能真正启动它,否则您会收到 TypeError 说:TypeError: can't send non-None value to a just-started generator跨度>
      【解决方案3】:

      您可以使用send 函数将值发送到生成器。

      如果你执行:

      p = protocol()
      p.next() # advance to the yield statement, otherwise I can't call send
      p.send(5)
      

      那么yield 将返回 5,因此在生成器内部c 将是 5。

      另外,如果您调用p.next()yield 将返回None

      您可以找到更多信息here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-11-19
        • 1970-01-01
        • 1970-01-01
        • 2018-02-22
        • 2019-09-10
        • 2015-10-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多