what does yield as assignment do? myVar = (yield)

后端 未结 3 1081
滥情空心
滥情空心 2020-12-29 20:13

I\'m familiar with yield to return a value thanks mostly to this question

but what does yield do when it is on the right side of an assignment?

@cor         


        
3条回答
  •  北荒
    北荒 (楼主)
    2020-12-29 20:46

    • yield returns a stream of data as per the logic defined within the generator function.
    • However, send(val) is a way to pass a desired value from outside the generator function.

    p.next() doesn't work in python3, next(p) works (built-in) for both python 2,3

    p.next() doesn't work with python 3, gives the following error,however it still works in python 2.

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

    Here's a demonstration:

    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
    
    

提交回复
热议问题