https://www.cnblogs.com/xuexianqi/p/12564614.html

def dog(name):
    print('道哥%s准备吃东西了...' % name)
    while True:
        # x拿到的是yield接收到的值
        x = yield  # x = '一根骨头'
        print('道哥%s吃了 %s' % (name, x))


g = dog('alex')

g.send(None)  # 等同于next(g),先完成初始化

g.send('一根骨头')
# g.send('一根骨头','肉包子')    # 不能传2个值,会报错:TypeError: send() takes exactly one argument (2 given)
g.send(['一根骨头','肉包子'])    # 可以放到列表里传输,列表算是一个值
g.send('肉包子')
g.send('一桶泔水')
# g.close()
# g.send('1111') # 关闭之后无法传值

二:综合应用

def dog(name):
    food_list = []
    print('大哥%s准备吃东西了...' % name)
    while True:
        # x拿到的是yield接收到的值
        # x = yield 111 # x = ['一根骨头','肉包子']
        x = yield food_list # x = ['一根骨头','肉包子']
        print('大哥%s抽了 %s' % (name, x))
        food_list.append(x)


g = dog('egon')

res = g.send(None)  # 等同于next(g),先完成初始化
print(res)

res = g.send(['一个鞭炮','一根烟'])
print(res)

res = g.send('一个地雷')
print(res)
def func():
    print('start...')
    x = yield 111
    print('H哈哈')
    print('H哈哈')
    print('H哈哈')
    yield 222

g = func()
res = next(g)
print(res)

res = g.send('xxxx')
print(res)

相关文章:

  • 2021-12-18
  • 2021-12-18
  • 2021-12-18
  • 2021-12-24
  • 2022-01-04
猜你喜欢
  • 2021-06-01
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-11
  • 2021-12-24
  • 2022-12-23
相关资源
相似解决方案